项目大体思路是这样的:先准备俩张图片,提取特征向量然后存储起来,让后拿第三章人脸图片来检测,查看是否匹配,匹配则输出名字和图像。
主要方法:

demo:
- # 1、加载库
- import face_recognition
- import cv2
- import numpy as np
- # 2、加载图片
- fei =cv2.imread("../images/liyifei3.jpg")
- en = cv2.imread("../images/chenqiaoen.jpg")
- # 3、BGR转换RGB(逆序)
- fei_RGB = fei[:,:,::-1]
- en_RGB = en[:,:,::-1]
- # 4、检测人脸
- fei_face = face_recognition.face_locations(fei_RGB)
- en_face = face_recognition.face_locations(en_RGB)
- # 5、人脸特征编码
- fei_encoding = face_recognition.face_encodings(fei_RGB,fei_face)[0] #0表示第一张人脸
- en_encoding = face_recognition.face_encodings(en_RGB,en_face)[0]
- # 6、把所有人脸组合在一起,当数据库使用
- encodings = [fei_encoding,en_encoding]
- names = ["liyifei","chenqiaoen"]
- # 7、打开摄像头,读取视频流
- cap = cv2.VideoCapture(0)
-
- if not cap.isOpen():
- raise IOError("Camera Rrror")
- while True:
- ret,frame = cap.read()
- #调整窗口大小为一半
- frame = cv2.resize(frame,(0,0),fx=0.5,fy=0.5)
- # 8、BRG转换RGB
- frame_RGB = frame[:,:,::-1]
- # 9、读取每一帧,人脸检测
- faces_locations = face_recognition.face_locations(frame_RGB)
- # 10、人脸特征编码
- facces_locations = face_recognition.face_encodings(frame_RGB,faces_locations)
- # 11、与数据库中的所有人脸进行匹配(拿到对应的特征和编码)
- for (top,right,bottom,left),face_encoding in zip(faces_locations,faces_locations):
- # 12、进行匹配
- matches = face_recognition.compare_faces(encodings,face_encoding)
- # 13、计算俩张图片的欧氏距离
- distance = face_recognition.face_distance(encodings,face_encoding)
- min_distance = np.argmin(distance) #0,1,2
- # 14、判断距离,很近是同一个人,如果很远就不是同一个人,获取名字,匹配或取名字,不匹配返货unkonw
- name = "Unknown"
- if matches[min_distance]:
- name = names[min_distance]
-
- # 15、人脸画矩形框和名称
- cv2.rectangle(frame,(left,top),(top,right),(0,255,0),3)
- # 16、绘制显示对应人脸的名字
- cv2.rectangle(frame,(left,bottom-30),(right,bottom),(0,0,255),3)
- # 17、显示名字
- cv2.putText(frame,name,(left+10,bottom-10),cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),1)
- #判断是q按键,退出
- cv2.imshow("face recoginition",frame)
- if cv2.waitKey(1) & 0xFF == ord('q'):
- break
- # 18、释放资源
- cap.release()
- cv2.destroyAllWindows()
-
-
-
-
-
-