示例下载链接
import cv2
import numpy as np
import face_recognition
import os
path = 'MyPic'
images = []
classNames = []
myList = os.listdir(path)
for cl in myList:
curImg = cv2.imread(f'{path}/{cl}')
#读取文件夹中的图片数据
images.append(curImg)
classNames.append(os.path.splitext(cl)[0])
print(classNames)
#传入上面读取的所有图片数据
def findEncoding(images):
encodeList = []
for img in images:
#将图片转成RGB格式
img = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)
#对所有图片数据进行编码
encode = face_recognition.face_encodings(img)[0]
encodeList.append(encode)
return encodeList
#获取文件夹中所有编码后的图片数据
encodeListKnown = findEncoding(images)
print(len(encodeListKnown))
cap = cv2.VideoCapture(0)
while True:
#获取摄像头数据
success,img = cap.read()
#等比例缩小
imgS = cv2.resize(img,(0,0),None,0.25,0.25)
#转换成RGB格式
imgS = cv2.cvtColor(imgS, cv2.COLOR_RGB2BGR)
#获取每一帧的人脸位置数据 无则返回空
facesCurFrame = face_recognition.face_locations(imgS)
# 获取每一帧的人脸数据编码 无则返回空
encodesCurFrame = face_recognition.face_encodings(imgS,facesCurFrame)
#若上面检测到人脸,则进入下面判断 for... in... zip 并行遍历,同时遍历两个列表
for encodeFace,faceLoc in zip(encodesCurFrame,facesCurFrame):
matches = face_recognition.compare_faces(encodeListKnown,encodeFace)
faceDis = face_recognition.face_distance(encodeListKnown,encodeFace)
print(faceDis,matches)
cv2.imshow("Image", imgS)
cv2.waitKey(1)
# imgElon = face_recognition.load_image_file('MyPic/6.jpg')
# imgElon = cv2.cvtColor(imgElon,cv2.COLOR_RGB2BGR)
# imgTest = face_recognition.load_image_file('MyPic/3.jpg')
# imgTest = cv2.cvtColor(imgTest,cv2.COLOR_RGB2BGR)
打开摄像头后,将打印的头像与库中已有头像进行识别,第二张和最后一张图像与摄像头拍摄人脸相同,识别成功。