Python 实现简单人脸识别:核心库与三十行代码详解
本文详解使用Python进行简单人脸识别的实现过程。重点介绍OpenCV、face_recognition及dlib库的安装注意事项,包括国内镜像源更换及特定版本dlib的whl文件配置。通过三十行核心代码,演示如何加载图片、提取人脸特征编码、定位人脸位置,并结合视频流进行实时比对识别,提供完整的代码注释与逻辑解析。
一、库介绍
本方案主要依赖四个Python库:OpenCV用于图像处理,face_recognition提供高层级的人脸识别接口,NumPy处理数组数据,以及dlib作为底层特征提取引擎。
注意: 安装OpenCV时速度可能较慢,建议更换国内镜像源,具体参考:https://www.jb51.net/article/208359.htm 此外,需附带Python3.7(64位版本)对应的dlib whl文件,下载路径为:dlib-19_jb51.rar
二、库安装
pip install opencv-python
pip install face_recognition
pip install numpy
dlib库的安装需先进入whl文件所在的目录路径,再执行安装命令。
pip install dlib-19.17.99-cp37-cp37m-win_amd64.whl
三、face_recognition库简单介绍
face_recognition库中的load_image_file方法负责加载图片文件,并返回一个ndarray类型的数据对象。
face_path = "C://Users//25103//Desktop//Python人脸识别//face//徐先生.jpg"
image = face_recognition.load_image_file(face_path)
face_recognition库中的face_encoding方法,能够从上述返回的ndarray类型数据中提取人脸特征向量。该方法支持同时提取多个特征,最终返回值为列表类型。
face_encoding = face_recognition.face_encodings(image)[0]
face_recognition库中的face_location方法用于获取图片中所有人脸的边界框位置,其返回值为一个包含位置信息的列表。
face_locations = face_recognition.face_locations(rgb_frame)
四、代码实现以及注释讲解
# coding = utf-8
import dlib
import cv2
import face_recognition
import os
# 创建视频对象
video_capture = cv2.VideoCapture(0)
# 加载需要识别的人脸图片(这张图片需要仅有一张脸)
# face_recognition的load_image_file方法会加载图片,并返回一个ndarray类型的数据
# ndarray类型就是NumPy的数组类型,其中的元素类型可以一致也可以不一致
face_path = "C://Users//25103//Desktop//Python人脸识别//face//徐先生.jpg"
image = face_recognition.load_image_file(face_path)
# face_recognition的face_encoding方法,可从返回的ndarray类型数据中提取人脸特征,可同时提取多个特征,返回值为列表类型
# 因为照片中只有一个人脸,所以我们取列表的第一个值
face_encoding = face_recognition.face_encodings(image)[0]
while True:
# 从视频对象中读取一帧照片
ret,frame = video_capture.read()
# 将照片缩小,加快处理速度,这里将其缩小为原图的1/4
# frame = cv2.rectangle(frame,(0,0),fx=0.25,fy=0.25)
# 因为cv2用的是BGR色彩,我们组要将其转化为RGB进行处理
rgb_frame = frame[:,:,::-1] # 列表转置操作
# face_recognition的face_location方法可以获取图片中所有人脸的位置,其返回值为一个列表
face_locations = face_recognition.face_locations(rgb_frame)
print("共从视频中找到了{}张人脸".format(len(face_locations)))
# 获取视频中所有人脸的特征
face_encodings = face_recognition.face_encodings(rgb_frame,face_locations)
for face in face_encodings:
# 比较两个特征值——encoding1与encoding2,匹配返回True,否则返回False。tolerance越低,顾名思义,容错率越低,返回值为列表类型
match = face_recognition.compare_faces([face_encoding],face,tolerance=0.4)
name = "不认识的人"
if match[0]:
# face为图片名称
name = os.path.basename(face_path[0:-4])
print("找到了{}".format(name))
到此这篇关于Python三十行代码实现简单人脸识别的示例代码的文章就介绍到这了,更多相关Python 简单人脸识别内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









