opencv人脸识别face_recognition
使用opencv,face_recognition人脸识别
1 # -*- coding: utf-8 -*- 2 # 摄像头头像识别 3 import face_recognition 4 import cv2 5 6 video_capture = cv2.VideoCapture(0) 7 8 # 本地图像 9 chenduling_image = face_recognition.load_image_file("zhouyu.jpg") 10 chenduling_face_encoding = face_recognition.face_encodings(chenduling_image)[0] 11 12 # 本地图像二 13 sunyizheng_image = face_recognition.load_image_file("zhouhanmin.jpg") 14 sunyizheng_face_encoding = face_recognition.face_encodings(sunyizheng_image)[0] 15 16 # 本地图片三 17 zhangzetian_image = face_recognition.load_image_file("heyuji.jpg") 18 zhangzetian_face_encoding = face_recognition.face_encodings(zhangzetian_image)[0] 19 20 # Create arrays of known face encodings and their names 21 # 脸部特征数据的集合 22 known_face_encodings = [ 23 chenduling_face_encoding, 24 sunyizheng_face_encoding, 25 zhangzetian_face_encoding 26 ] 27 28 # 人物名称的集合 29 known_face_names = [ 30 "zhouyu", 31 "zhouhanmin", 32 "heyuji" 33 ] 34 35 face_locations = [] 36 face_encodings = [] 37 face_names = [] 38 process_this_frame = True 39 40 while True: 41 # 读取摄像头画面 42 ret, frame = video_capture.read() 43 44 # 改变摄像头图像的大小,图像小,所做的计算就少 45 small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25) 46 47 # opencv的图像是BGR格式的,而我们需要是的RGB格式的,因此需要进行一个转换。 48 rgb_small_frame = small_frame[:, :, ::-1] 49 50 # Only process every other frame of video to save time 51 if process_this_frame: 52 # 根据encoding来判断是不是同一个人,是就输出true,不是为flase 53 face_locations = face_recognition.face_locations(rgb_small_frame) 54 face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations) 55 56 face_names = [] 57 for face_encoding in face_encodings: 58 # 默认为unknown 59 matches = face_recognition.compare_faces(known_face_encodings, face_encoding) 60 name = "Unknown" 61 62 # if match[0]: 63 # name = "michong" 64 # If a match was found in known_face_encodings, just use the first one. 65 if True in matches: 66 first_match_index = matches.index(True) 67 name = known_face_names[first_match_index] 68 face_names.append(name) 69 70 process_this_frame = not process_this_frame 71 72 # 将捕捉到的人脸显示出来 73 for (top, right, bottom, left), name in zip(face_locations, face_names): 74 # Scale back up face locations since the frame we detected in was scaled to 1/4 size 75 top *= 4 76 right *= 4 77 bottom *= 4 78 left *= 4 79 80 # 矩形框 81 cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) 82 83 #加上标签 84 cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) 85 font = cv2.FONT_HERSHEY_DUPLEX 86 cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) 87 88 # Display 89 cv2.imshow('monitor', frame) 90 91 # 按Q退出 92 if cv2.waitKey(1) & 0xFF == ord('q'): 93 break 94 95 video_capture.release() 96 cv2.destroyAllWindows()

浙公网安备 33010602011771号