1 face_recognition 及其他几个重要包的安装
我是在树莓派下安装的
$ sudo apt-get install build-essential cmake
$ sudo apt-get install libgtk-3-dev
$ sudo apt-get install libboost-all-dev
$ pip3 install numpy
$ pip3 install scipy
$ pip3 install opencv-python
$ pip3 install dlib
$ pip3 install cmake
$ pip3 install face_recognition
代码
import sys
import face_recognition as f #人脸识别库
import cv2 #opencv库
#读取图片
face_image = f.load_image_file("a.jpg")
#返回这张图片的128位人脸编码
face_encodings = f.face_encodings(face_image)
face_locations = f.face_locations(face_image)
n = len(face_encodings)
print(n) #打印出来的是人脸的个数
if n > 2: #如果识别出来图片内的人脸数>2
print('too many face')
sys.exit()
try: #如果恰好两张脸,就把这两张脸赋给face1 face2
face1 = face_encodings[0]
face2 = face_encodings[1]
except:
print("plesae input a face")
sys.exit()
# 用库中的函数来比较人脸,返回值是布尔值
results = f.compare_faces([face1],face2,tolerance = 0.4)
#tolerance 代表比较的精度越小越严格
if results == [True]:
print("True")
temp = "match"
else:
print("False")
temp = "Mismatch"
#对原图片进行绘制
for i in range(len(face_encodings)):
face_encoding = face_encodings[(i-1)] #遍历时逆序的选择列表中的两张脸
face_location = face_locations[(i-1)]
print(face_location) #face_location的返回值是脸的位置值
top,right,bottom,left = face_location
# 绘制矩形 从 左上角 到 右下角 颜色 粗细
cv2.rectangle(face_image,(left,top),(right,bottom),(0,255,0),2)
# 写入文字 文字内容 文字位置 字体 字体大小 颜色 粗细
cv2.putText(face_image,temp,(left-10,top-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,0,0),2)
#将画好的图像 以RGB的形式打开 并保存
face_image_rgb = cv2.cvtColor(face_image,cv2.COLOR_BGR2RGB)
cv2.imshow("view",face_image_rgb)
cv2.imwrite("/home/pi/Desktop/ 2.jpg",face_image_rgb,[int(cv2.IMWRITE_JPEG_QUALITY),100])
cv2.waitKey(0)