宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

这篇文章给大家分享的是有关Python如何使用face_recognition实现AI识别图片中的人物的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

环境安装

首先我们看看官方给出的人脸识别效果图

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

我们看一下README关于安装环境的信息

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

官方给出的可安装操作系统是Mac和Linux,但是我想在windows安装,继续往下看。

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

windows虽然不是官方支持,但是也能装,不就是个dlib吗?好的,那就开始装。

我们直接安装requirements_dev.txt,这里要注意,把pip去掉。

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

注意一点安装dlib的时候会报错,需要先安装cmake,安装命令如下:

pip install cmake -i https://pypi.douban.com/simple

除此之外,项目还需要安装opencv-python,安装命令如下:

pip install opencv-python -i https://pypi.douban.com/simple

代码使用

先做一下说明,在使用face_recognition运行的时候,可以选择安装face_recognition命令进行运行的模式,也可以使用face_recognition模块构建代码运行。为了二次开发,我还是先试试代码的方式,主要试试人脸识别模块。

官方代码如下:

import face_recognition

# Load the jpg files into numpy arrays
biden_image = face_recognition.load_image_file"biden.jpg")
obama_image = face_recognition.load_image_file"obama.jpg")
unknown_image = face_recognition.load_image_file"obama2.jpg")

# Get the face encodings for each face in each image file
# Since there could be more than one face in each image, it returns a list of encodings.
# But since I know each image only has one face, I only care about the first encoding in each image, so I grab index 0.
try:
    biden_face_encoding = face_recognition.face_encodingsbiden_image)[0]
    obama_face_encoding = face_recognition.face_encodingsobama_image)[0]
    unknown_face_encoding = face_recognition.face_encodingsunknown_image)[0]
except IndexError:
    print"I wasn't able to locate any faces in at least one of the images. Check the image files. Aborting...")
    quit)

known_faces = [
    biden_face_encoding,
    obama_face_encoding
]

# results is an array of True/False telling if the unknown face matched anyone in the known_faces array
results = face_recognition.compare_facesknown_faces, unknown_face_encoding)

print"Is the unknown face a picture of Biden? {}".formatresults[0]))
print"Is the unknown face a picture of Obama? {}".formatresults[1]))
print"Is the unknown face a new person that we've never seen before? {}".formatnot True in results))

代码说明:

1、首先可以看到将两个人脸的数据加到了known_faces列表内。

2、然后用未知图数据进行识别判断。

看一下加入到known_faces的照片

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

看一下需要识别的照片

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

看一下执行结果

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

我们可以看到在拜登的识别中提示false,在奥巴马识别中提示true。这里要注意一点,我们看一下compare_faces方法参数。

Python如何使用face_recognition实现AI识别图片中的人物-风君子博客

参数tolerance最佳为0.6,越低越严格,所以可以按照自己的需求调整。