怎样用3分钟搭建 Python 人脸识别系统

最近更新时间 2021-01-05 14:01:04

Face Recognition 使用的是 C++ 开源库 dlib 通过深度学习模型构建的先进人脸识别系统,可通过 Python 接口或命令行工具对图片中的人脸进行识别。在 Labeled Faces in the Wild 人脸数据集中进行测试,准确率高达99.38%。可以使用 Face Recognition 软件包快速搭建人脸识别系统。

安装

使用 pip 命令安装 face_recognition 软件包,官方支持 Mac 和 Linux 系统,另外也支持在树莓派上安装。如果系统中没有 CMake 安装时可能报错,按错误提示解决即可。

pip install face_recognition
Successfully built dlib face-recognition-models
Installing collected packages: Pillow, numpy, face-recognition-models, dlib, Click, face-recognition
Successfully installed Click-7.1.2 Pillow-8.1.0 dlib-19.21.1 face-recognition-1.3.0 face-recognition-models-0.3.0 numpy-1.19.4

示例一:识别图片中的人脸

下面的示例中使用 face_locations 方法获取图片中人脸的位置,再根据位置在原图上画框。

# coding=utf-8

"""
测试识别图片中的人脸
"""
from PIL import Image, ImageDraw
import face_recognition

# 加载图片
image = face_recognition.load_image_file("unknown.jpg")
# 识别人脸,返回位置坐标
# 返回结果为列表,坐标数据 (top, right, bottom, left)
face_locations = face_recognition.face_locations(image)

# 创建图片用于显示识别效果
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)

for face_location in face_locations:

    # 根据人脸识别的坐标画框
    top, right, bottom, left = face_location
    d.rectangle(((left, top), (right, bottom)), outline=(255, 0, 0), width=3)

# 显示图片
pil_image.show()
# 保存为新文件
# pil_image.save("output.jpg")

输出结果如下下图所示:

Biden

示例二:提取面部关键点

下面的示例使用 face_landmarks 函数获取图片中面部特征位置(如眼睛、鼻子等)信息。

# coding=utf-8

"""
测试识别面部关键点
"""
from PIL import Image, ImageDraw
import face_recognition

# 加载图片
image = face_recognition.load_image_file("unknown.jpg")
# 获取图片中面部特征位置
face_landmarks_list = face_recognition.face_landmarks(image)

# 创建图片用于显示识别效果
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)

for face_landmarks in face_landmarks_list:

    # 根据特征位置在原图上画线
    for facial_feature in face_landmarks.keys():
        d.line(face_landmarks[facial_feature], width=5)

# 显示图片
# pil_image.show()
# 保存为新文件
pil_image.save("output.jpg")

输出结果如下下图所示:

Biden

Face Recognition 还可用于人脸比对,视频人脸识别等。

rss_feed