開發環境和用到的庫:python
實現效果以下(視頻截圖):app
1 #coding=utf-8 2 #人臉識別類 - 使用face_recognition模塊 3 import cv2 4 import face_recognition 5 import os 6 7 path = "img/face_recognition" # 模型數據圖片目錄 8 cap = cv2.VideoCapture(0) 9 total_image_name = [] 10 total_face_encoding = [] 11 for fn in os.listdir(path): #fn 表示的是文件名q 12 print(path + "/" + fn) 13 total_face_encoding.append( 14 face_recognition.face_encodings( 15 face_recognition.load_image_file(path + "/" + fn))[0]) 16 fn = fn[:(len(fn) - 4)] #截取圖片名(這裏應該把images文件中的圖片名命名爲爲人物名) 17 total_image_name.append(fn) #圖片名字列表 18 while (1): 19 ret, frame = cap.read() 20 # 發如今視頻幀全部的臉和face_enqcodings 21 face_locations = face_recognition.face_locations(frame) 22 face_encodings = face_recognition.face_encodings(frame, face_locations) 23 # 在這個視頻幀中循環遍歷每一個人臉 24 for (top, right, bottom, left), face_encoding in zip( 25 face_locations, face_encodings): 26 # 看看面部是否與已知人臉相匹配。 27 for i, v in enumerate(total_face_encoding): 28 match = face_recognition.compare_faces( 29 [v], face_encoding, tolerance=0.5) 30 name = "Unknown" 31 if match[0]: 32 name = total_image_name[i] 33 break 34 # 畫出一個框,框住臉 35 cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 255), 2) 36 # 畫出一個帶名字的標籤,放在框下 37 cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 255, 255), 38 cv2.FILLED) 39 font = cv2.FONT_HERSHEY_DUPLEX 40 cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, 41 (255, 255, 255), 1) 42 # 顯示結果圖像 43 cv2.imshow('Video', frame) 44 if cv2.waitKey(1) & 0xFF == ord('q'): 45 break 46 47 cap.release() 48 cv2.destroyAllWindows()