1,简介
本案例使用face_recognition,它是OpenCV中一个基于深度学习的人脸识别模块。使用face_recognition,你可以输入一张图像或一段视频流或者调用摄像头,然后对其中的人脸进行识别和标注。其核心功能是将图像中的人脸进行编码,然后与已有的人脸编码进行比对,从而进行人脸识别。(以下的代码后面有相应的解释说明)
2,人脸相似度对比
代码:
import cv2
import numpy as np
import face_recognition
imgElon = face_recognition.load_image_file('ImagesBasic/Luke/lucked.png') # 加载图片
imgElon = cv2.cvtColor(imgElon, cv2.COLOR_BGR2RGB) # 将BGR彩色图像转化为RGB彩色图像
imgTest = face_recognition.load_image_file('ImagesBasic/Emo/Musk.jpg')
imgTest = cv2.cvtColor(imgTest, cv2.COLOR_BGR2RGB)
faceLoc = face_recognition.face_locations(imgElon)[0] # 定位人脸位置
encodeElon = face_recognition.face_encodings(imgElon)[0] # 提取人脸的面部特征
cv2.rectangle(imgElon, (faceLoc[3], faceLoc[0]), (faceLoc[1], faceLoc[2]), (255, 0, 255), 2) # 框出人脸
# print(faceLoc)
faceLocTest = face_recognition.face_locations(imgTest)[0]
encodeTest = face_recognition.face_encodings(imgTest)[0]
cv2.rectangle(imgTest, (faceLocTest[3], faceLocTest[0]), (faceLocTest[1], faceLocTest[2]), (255, 0, 255), 2)
result = face_recognition.compare_faces([encodeElon], encodeTest) # 比较人脸编码的相似度
faceDis = face_recognition.face_distance([encodeElon], encodeTest) # 计算两个人脸的欧氏距离(欧氏距离用于计算样本之间的相似度或距离)
print(result, faceDis)
cv2.putText(imgTest, f'{result}{round(faceDis[0], 2)}', (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2) # 显示比对结果
cv2.imshow('Emo Musk', imgElon)
cv2.imshow('Emo Test', imgTest)
key = cv2.waitKey(0)
if key == 27: # 按ESC键退出
cv2.destroyAllWindows()
效果:
3,人脸匹配
调用摄像头获取人人脸并与已有的人脸库进行匹配
温馨提示:
要自己创建Attendance.csv文件,即可实现以下功能
代码:
import cv2
import numpy as np
import face_recognition
import os
from datetime import datetime
path = 'ImagesBasic' # 人像存储位置
images = []
className = []
myList = os.listdir(path) # 返回指定文件目录下的列表,这里返回的是人像图片
print(myList)
for cl in myList: # 获取每张人像的名称
curImg = cv2.imread(f'{path}/{cl}')
images.append(curImg)
className.append(os.path.splitext(cl)[0])
print(className)
def findEncodings(images): # 获取所有存储的人像编码
encodeList = []
for img in images:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
encode = face_recognition.face_encodings(img)[0]
encodeList.append(encode)
return encodeList
def markAttendance(name): # 打卡,生成记录
with open('Attendance.csv', 'r+') as f:
myDatalist = f.readlines() # 读取文件中所有的行
nameList = []
for line in myDatalist:
entry = line.split(',')
nameList.append(entry[0])
if name not in nameList:
now = datetime.now()
dtString = now.strftime('%H:%M:%S') # 将日期时间格式化成字符串
f.writelines(f'\n{name},{dtString}') # 将包含多个字符串的可迭代对象写入文件中,这里是记录人名
encodeListKnown = findEncodings(images)
print('encoding complete')
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
imgs = cv2.resize(img, (0, 0), None, 0.25, 0.25) # 调整图片大小
imgs = cv2.cvtColor(imgs, cv2.COLOR_BGR2RGB)
faceCurFrame = face_recognition.face_locations(imgs) # 获取人脸位置信息
encodesCurFrame = face_recognition.face_encodings(imgs, faceCurFrame) # 获取人脸编码
for encodeFace, faceLoc in zip(encodesCurFrame, faceCurFrame): # zip函数,连接成字典
matches = face_recognition.compare_faces(encodeListKnown, encodeFace) # 人脸匹配度
faceDis = face_recognition.face_distance(encodeListKnown, encodeFace) # 欧式距离
# print(faceDis)
matchIndex = np.argmin(faceDis) # 返回数组中小元素的索引
if matches[matchIndex]:
name = className[matchIndex].upper()
print(name)
y1, x2, y2, x1 = faceLoc # 人脸位置
y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 1)
cv2.rectangle(img, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
cv2.putText(img, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
markAttendance(name) # 记录人名
cv2.imshow(str('Face_Detector'), img)
if cv2.waitKey(1) & 0xff == 27:
break
效果:
本文来自对csdn作者大大Cameo
的个人实践梳理,方便下次使用