睿智的目标检测14——face_recognition人脸识别库的安装与简要使用
学习前言
我死了我死了我死了!
什么是face_recognition
face_recognition是一个基于python的开源的人脸识别库,据说识别准确率达到了99.38%,效果比较好!代码网址为:https://github.com/ageitgey/face_recognition
安装步骤(Windows)
1、下载dlib的whl
点击链接:https://pypi.org/simple/dlib/。
下载“dlib-19.7.0-cp36-cp36m-win_amd64.whl“安装包。
face_recognition在Windows上使用貌似需要dlib-19.6以上的版本,因此建议大家安装python3.6。
下载完后呢,进入目标文件夹,进行whl的安装。
2、安装face_recognition
利用如下代码进行face_recognition的安装。
pip install face_recognition
之后就能完成安装了!
简要使用方法
摆放格式如下,face_dataset用于放人脸:
face_recognition的使用demo
import face_recognition
import numpy as np
import cv2
import os
class face_rec():
def __init__(self):
#-----------------------------------------------#
# 对数据库中的人脸进行编码
# known_face_encodings中存储的是编码后的人脸
# known_face_names为人脸的名字
#-----------------------------------------------#
face_list = os.listdir("face_dataset")
self.known_face_encodings=[]
self.known_face_names=[]
for face in face_list:
name = face.split(".")[0]
image = face_recognition.load_image_file("./face_dataset/"+face)
face_encoding = face_recognition.face_encodings(image)[0]
self.known_face_encodings.append(face_encoding)
self.known_face_names.append(name)
def recognize(self,draw):
#-----------------------------------------------#
# 人脸识别
# 先定位,再进行数据库匹配
#-----------------------------------------------#
height,width,_ = np.shape(draw)
draw_rgb = cv2.cvtColor(draw,cv2.COLOR_BGR2RGB)
# 根据上述参数进行人脸检测
# face_locations的格式为(top, right, bottom, left)
face_locations = face_recognition.face_locations(draw_rgb, number_of_times_to_upsample=1, model="hog")
if(len(face_locations) == 0):
return draw
# 批量编码
face_encodings = face_recognition.face_encodings(draw_rgb, face_locations)
face_names = []
for face_encoding in face_encodings:
# 取出一张脸并与数据库中所有的人脸进行对比,计算得分
matches = face_recognition.compare_faces(self.known_face_encodings, face_encoding, tolerance = 0.4)
name = "Unknown"
# 找出距离最近的人脸
face_distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
# 取出这个最近人脸的评分
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = self.known_face_names[best_match_index]
face_names.append(name)
#-----------------------------------------------#
# 画框~!~
#-----------------------------------------------#
for (top, right, bottom, left), name in zip(face_locations, face_names):
print(top, right, bottom, left)
if top < 0:
top = 0
if left < 0:
left = 0
if right > width:
right = width
if bottom > height:
bottom = height
cv2.rectangle(draw, (left, top), (right, bottom), (0, 0, 255), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(draw, name, (left , bottom - 15), font, 0.75, (255, 255, 255), 2)
return draw
if __name__ == "__main__":
dududu = face_rec()
video_capture = cv2.VideoCapture(0)
while True:
ret, draw = video_capture.read()
dududu.recognize(draw)
cv2.imshow('Video', draw)
if cv2.waitKey(20) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()