face_recognition是一款免费、开源、实时、离线的Python人脸识别库。Github网址为https://github.com/ageitgey/face_recognition。如安装Anaconda可直接跳到第二步,dlib会自动获取。
Windows系统安装dlib可直接在网站https://pypi.org/simple/dlib/ 下载对应版本的whl文件,用pip安装,简单高效。
安装face_recognition需要首先安装dlib。看网上教程需要编译dlib库,感觉比较麻烦。这里使用conda安装dlib。这anaconda.org上搜索到dlib19.9版本的安装命令为 conda install -c menpo dlib
由于ubuntu系统没有安装conda,因此需要安装,通过pip方式安装conda会提示问题,也会提示去下载miniconda,下载对应系统的版本,我这里下载了Miniconda2-latest-Linux-x86_64.sh。复制到home目录下,这终端中输入命令安装
sh Miniconda2-latest-Linux-x86_64.sh
安装完成后重启终端并输入如下命令切换镜像
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
其次再输入安装dlib的命令即 conda install -c menpo dlib。等待一段时间完成安装dlib,网速越好下载越快等待时间越短。
conda install -c menpo dlib
安装完dlib后安装face_recognition,命令如下,这次等待的时间需要几十分钟。
pip install face_recognition
(1)从本地读图片并使用face_recognition和opencv识别人脸并标注显示
#读取照片并圈出人脸
import numpy as np
import cv2
import face_recognition
image = face_recognition.load_image_file("mypic.jpg")
#return (A,B,C,D)(top, right, bottom, left) (D,A,B,C)
face_locations = face_recognition.face_locations(image)
print(face_locations)
image1=image*1
image1[:,:,0]=image[:,:,2]
image1[:,:,2]=image[:,:,0]
for (A,B,C,D) in face_locations:
cv2.rectangle(image1,(D,A),(B,C),(0,255,0),2)
cv2.imshow('image',image1)
cv2.waitKey(0)
cv2.destroyAllWindows()
图片来源网络,侵删
(2)从摄像头读取图像并显示
#摄像头读取并识别人脸
import numpy as np
import cv2
import face_recognition
cap=cv2.VideoCapture(0)
while True:
ret,frame=cap.read()
#return (A,B,C,D)(top, right, bottom, left) (D,A,B,C)
face_locations = face_recognition.face_locations(frame)
for (A,B,C,D) in face_locations:
cv2.rectangle(frame,(D,A),(B,C),(0,255,0),2)
cv2.imshow('image',frame)
if cv2.waitKey(1)& 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
(3)人脸比对
#人脸比对,单对单的比对,和多对单的比对
import numpy as np
import cv2
import face_recognition
zhujun=face_recognition.face_encodings(face_recognition.load_image_file('zhujun.jpg'))
dongqing=face_recognition.face_encodings(face_recognition.load_image_file('dongqing.jpg'))
#ss=face_recognition.compare_faces([dongqing,lisisi],zhujun)
#hezhao=face_recognition.face_encodings(face_recognition.load_image_file('mypic.jpg'))
#ss=face_recognition.compare_faces(hezhao,lisisi,0.5)
hezhao=face_recognition.load_image_file('mypic.jpg')
locations=face_recognition.face_locations(hezhao)
for [A,B,C,D] in locations:
face=hezhao[A:C,D:B,:]
faceencoding=face_recognition.face_encodings(face)
ss=face_recognition.compare_faces(faceencoding,zhujun[0],0.5)
print(ss)
输出结果,compare_faces的第三个参数越小表示要求的精度更高