1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
| import dlib import numpy import numpy as np import cv2 import pandas as pd import wx import os import csv import datetime import _thread
import Sub_Client import readSql import win32api,win32con
'''
移动侦测 @author czq @date 2020 12 28
'''
facerec = dlib.face_recognition_model_v1("model/dlib_face_recognition_resnet_model_v1.dat")
detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('model/shape_predictor_68_face_landmarks.dat')
loading = 'icon/loading.png' pun_fail = 'icon/pun_fail.png' pun_repeat = 'icon/pun_repeat.png' pun_success = 'icon/pun_success.png'
path_logcat_csv = "data/logcat.csv" user_flag = 0
def read_csv_to_recoders(): recodes = [] if os.path.exists(path_logcat_csv): with open(path_logcat_csv, "r", newline="") as csvfiler: reader = csv.reader(csvfiler) for row in reader: recodes.append(row) else: with open(path_logcat_csv, "w", newline="") as csvfilew: writer = csv.writer(csvfilew) header = ["姓名", "日期", "时间"] writer.writerow(header) return recodes pass
def return_euclidean_distance(feature_1, feature_2): """
:param feature_1: 向量一 :param feature_2: 向量二 :return: diff or same """ feature_1 = np.array(feature_1) feature_2 = np.array(feature_2) try: dist = np.sqrt(np.sum(np.square(feature_1 - feature_2))) if dist > 0.4: return "diff" else: return "same" print("欧式距离: ", dist) except numpy.core._exceptions.UFuncTypeError as ne: print(ne)
path_feature_known_csv = "data/feature_all.csv"
csv_rd = pd.read_csv(path_feature_known_csv, header=None, encoding='gbk')
features_known_arr = []
for i in range(csv_rd.shape[0]): features_someone_arr = [] for j in range(0, len(csv_rd.iloc[i, :])): features_someone_arr.append(csv_rd.iloc[i, :][j]) features_known_arr.append(features_someone_arr) print("数据库人脸数:", len(features_known_arr))
def get_128d_features(img_gray): """
:param img_gray: 灰度图 :return: 人脸 """ dets = detector(img_gray, 1) shape = predictor(img_gray, dets[0]) face_des = facerec.compute_face_descriptor(img_gray, shape) return face_des
class PunchcardUi(wx.Frame): """ 移动侦测主界面 """
def __init__(self, superion): wx.Frame.__init__(self, parent=superion, title="catEye", size=(800, 590), style=wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP) self.SetBackgroundColour('white') self.Center()
self.OpenCapButton = wx.Button(parent=self, pos=(50, 120), size=(90, 60), label='开始检测')
self.resultText = wx.StaticText(parent=self, style=wx.ALIGN_CENTER_VERTICAL, pos=(50, 320), size=(90, 60), label="未知用户报警")
self.resultText.SetBackgroundColour('white') self.resultText.SetForegroundColour('blue') font = wx.Font(14, wx.DECORATIVE, wx.ITALIC, wx.NORMAL) self.resultText.SetFont(font)
self.pun_day_num = 0
self.image_loading = wx.Image(loading, wx.BITMAP_TYPE_ANY).Scale(600, 480)
self.image_fail = wx.Image(pun_fail, wx.BITMAP_TYPE_ANY).Scale(600, 480) self.image_repeat = wx.Image(pun_repeat, wx.BITMAP_TYPE_ANY).Scale(600, 480) self.image_success = wx.Image(pun_success, wx.BITMAP_TYPE_ANY).Scale(600, 480)
self.bmp = wx.StaticBitmap(parent=self, pos=(180, 20), bitmap=wx.Bitmap(self.image_loading))
self.Bind(wx.EVT_BUTTON, self.OnOpenCapButtonClicked, self.OpenCapButton)
def OnOpenCapButtonClicked(self, event):
"""使用多线程,子线程运行后台的程序,主线程更新前台的UI,这样不会互相影响""" _thread.start_new_thread(self._open_cap, (event,))
def _open_cap(self, event): global dets urlc = 'http://192.168.1.104:81/stream' localtime = datetime.datetime.now() date = str(localtime.year) + " " + str(localtime.month) + " " + str(localtime.day) time = str(localtime.hour) + " " + str(localtime.minute) + " " + str(localtime.minute) video_src = 'E:/czq/personFile/catCamera/src/server/data/video/catEye' + date + '.avi'
a = 0 self.cap = cv2.VideoCapture(video_src) self.cap.set(3, 480)
while self.cap.isOpened():
flag, im_rd = self.cap.read()
kk = cv2.waitKey(1) try: dets = detector(im_rd, 1) except TypeError as te: print(te) print('人脸数目获取错误!') font = cv2.FONT_HERSHEY_SIMPLEX
name = '' pos = '' count = 0 if len(dets) != 0:
features_cap = '' try: shape = predictor(im_rd, dets[0]) except TypeError as te: print(te) print('error!') features_cap = facerec.compute_face_descriptor(im_rd, shape)
name = "unrecognized face"
pos = tuple([(int)((dets[0].left() + dets[0].right()) / 2) - 50 , dets[0].bottom() + 20])
for i in range(len(features_known_arr)): self.pun_day_num = 0 compare = return_euclidean_distance(features_cap, features_known_arr[i][0:-1]) if compare == "same": name = features_known_arr[i][-1] recoder = [] recoder.append(name) localtime = datetime.datetime.now() date = str(localtime.year) + " " + str(localtime.month) + " " + str(localtime.day)+ ' ' time = str(localtime.hour) + " " + str(localtime.minute) + " " + str(localtime.minute) recoder.append(date) recoder.append(time) recoders = read_csv_to_recoders() filename = 'data/move_test_img/' + name + date + time + ".png" print(filename) cv2.imwrite(filename, im_rd) user_flag = 1 print(recoders) Sub_Client.upload_image(filename, 'faceImgRegister', 'face image register successful') readSql.move_test_save_data(name, filename, user_flag)
cv2.rectangle(im_rd, tuple([dets[0].left(), dets[0].top()]), tuple([dets[0].right(), dets[0].bottom()]), (255, 0, 0), 2)
cv2.putText(im_rd, name, pos, font, 0.8, (255, 0, 255), 1, cv2.LINE_AA)
if name == "unrecognized face": print("danger\r\n") import time import ctypes player = ctypes.windll.kernel32 player.Beep(1000, 200) for i in range(10): time.sleep(1) player.Beep(1000, 200) print('wx.MessageBox(message="有人入侵了", caption="可怕的消息")') localtime = datetime.datetime.now() date = str(localtime.year) + " " + str(localtime.month) + " " + str(localtime.day) + ' ' time = str(localtime.hour) + " " + str(localtime.minute) + " " + str(localtime.minute) user_flag = 0
filename = 'data/move_test_img/' + name + date + time + ".png" print(filename) cv2.imwrite(filename, im_rd) Sub_Client.upload_image(filename, 'faceRecognizeImage', 'face recognize successful') readSql.move_test_save_data(name, filename, user_flag)
cv2.putText(im_rd, "Faces: " + str(len(dets)), (50, 80), font, 1, (255, 0, 0), 1, cv2.LINE_AA)
try: height, width = im_rd.shape[:2] image1 = cv2.cvtColor(im_rd, cv2.COLOR_BGR2RGB) pic = wx.Bitmap.FromBuffer(width, height, image1) ''' bug 001 2020 01 16 ''' self.bmp.SetBitmap(pic) except AttributeError as ae: print(ae) print('人脸图片切割错误') except cv2.error as ce: print(ce) print('图片灰度化错误!') except RuntimeError as re: print(re) print('运行中程序出错')
|