文章目录
本文基于face_recognition库实现图像人脸识别,下面将介绍如何安装face_recognition库,并细述3个常用的人脸识别案例。
一、安装人脸识别库face_recognition
Face_recognition的安装不同于其他package,它需要依赖dlib库(dlib库的安装又依赖于cmake库),所以装face_recognition之前需要先安装前二者,整个安装过程还是挺耗费时间精力的。我的python环境是python3.7+Anaconda。
1.1 安装cmake
pip install cmake -i https://pypi.tuna.tsinghua.edu.cn/simple/
借助清华源的资源安装,通常下载速度会比较快,且不会中断。
1.2 安装dlib库
dlib-19.17.99-cp37-cp37m-win_amd64.whl 密码 79rt
下载后直接安装该whl文件
pip install dlib-19.17.99-cp37-cp37m-win_amd64.whl
直接在线pip install dlib,不知为何会报错,所以从网站上下载好安装包进行离线安装。
1.3 安装face_recognition
pip install face_recognition -i https://pypi.tuna.tsinghua.edu.cn/simple/
二、3个常用的人脸识别案例
本章主要介绍face_recognition下3个常用的人脸识别方法及案例,它们所依赖的库函数如下:
import os
import face_recognition as fr
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import dlib
import numpy as np
2.1 识别并绘制人脸框
其中,face_locations(img, number_of_times_to_upsample=1, model=“hog”) 方法为实现该demo的关键,该方法用于提取图像img中的人脸特征并返回所有人脸框坐标list。
def draw_face_rect(self):
self.img = fr.load_image_file(pic) # 读图
#(1)识别人脸框所在坐标
faces = fr.face_locations(self.img) # 也可使用cnn识别
# faces = fr.face_locations(self.img, number_of_times_to_upsample=0, model="cnn")
#(2)创建展示结果的图像
pil_img = Image.fromarray(self.img)
draw = ImageDraw.Draw(pil_img)
#(3)依次绘制人脸框
for face in faces:
top, right, bottom, left = face
draw.rectangle(((left, top), (right, bottom)), outline=(0,255,0))
del draw
plt.imshow(pil_img)
plt