Python基于Dlib的人脸识别系统的实现


Posted in Python onFebruary 26, 2020

之前已经介绍过人脸识别的基础概念,以及基于opencv的实现方式,今天,我们使用dlib来提取128维的人脸嵌入,并使用k临近值方法来实现人脸识别。

人脸识别系统的实现流程与之前是一样的,只是这里我们借助了dlib和face_recognition这两个库来实现。face_recognition是对dlib库的包装,使对dlib的使用更方便。所以首先要安装这2个库。

pip3 install dlib
pip3 install face_recognition

然后,还要安装imutils库

pip3 install imutils

我们看一下项目的目录结构:

.
├── dataset
│   ├── alan_grant [22 entries exceeds filelimit, not opening dir]
│   ├── claire_dearing [53 entries exceeds filelimit, not opening dir]
│   ├── ellie_sattler [31 entries exceeds filelimit, not opening dir]
│   ├── ian_malcolm [41 entries exceeds filelimit, not opening dir]
│   ├── john_hammond [36 entries exceeds filelimit, not opening dir]
│   └── owen_grady [35 entries exceeds filelimit, not opening dir]
├── examples
│   ├── example_01.png
│   ├── example_02.png
│   └── example_03.png
├── output
│   ├── lunch_scene_output.avi
│   └── webcam_face_recognition_output.avi
├── videos
│   └── lunch_scene.mp4
├── encode_faces.py
├── encodings.pickle
├── recognize_faces_image.py
├── recognize_faces_video_file.py
├── recognize_faces_video.py
└── search_bing_api.py
 
10 directories, 12 files

首先,提取128维的人脸嵌入:

命令如下:

python3 encode_faces.py --dataset dataset --encodings encodings.pickle -d hog

记住:如果你的电脑内存不够大,请使用hog模型进行人脸检测,如果内存够大,可以使用cnn神经网络进行人脸检测。

看代码:

# USAGE
# python encode_faces.py --dataset dataset --encodings encodings.pickle
 
# import the necessary packages
from imutils import paths
import face_recognition
import argparse
import pickle
import cv2
import os
 
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--dataset", required=True,
	help="path to input directory of faces + images")
ap.add_argument("-e", "--encodings", required=True,
	help="path to serialized db of facial encodings")
ap.add_argument("-d", "--detection-method", type=str, default="hog",
	help="face detection model to use: either `hog` or `cnn`")
args = vars(ap.parse_args())
 
# grab the paths to the input images in our dataset
print("[INFO] quantifying faces...")
imagePaths = list(paths.list_images(args["dataset"]))
 
# initialize the list of known encodings and known names
knownEncodings = []
knownNames = []
 
# loop over the image paths
for (i, imagePath) in enumerate(imagePaths):
	# extract the person name from the image path
	print("[INFO] processing image {}/{}".format(i + 1,
		len(imagePaths)))
	name = imagePath.split(os.path.sep)[-2]
 
	# load the input image and convert it from RGB (OpenCV ordering)
	# to dlib ordering (RGB)
	image = cv2.imread(imagePath)
	rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 
	# detect the (x, y)-coordinates of the bounding boxes
	# corresponding to each face in the input image
	boxes = face_recognition.face_locations(rgb,
		model=args["detection_method"])
 
	# compute the facial embedding for the face
	encodings = face_recognition.face_encodings(rgb, boxes)
 
	# loop over the encodings
	for encoding in encodings:
		# add each encoding + name to our set of known names and
		# encodings
		knownEncodings.append(encoding)
		knownNames.append(name)
 
# dump the facial encodings + names to disk
print("[INFO] serializing encodings...")
data = {"encodings": knownEncodings, "names": knownNames}
f = open(args["encodings"], "wb")
f.write(pickle.dumps(data))
f.close()

输出结果是每张图片输出一个人脸的128维的向量和对于的名字,并序列化到硬盘,供后续人脸识别使用。

识别图像中的人脸:

这里使用KNN方法实现最终的人脸识别,而不是使用SVM进行训练。

命令如下:

python3 recognize_faces_image.py --encodings encodings.pickle 	--image examples/example_01.png

看代码:

# USAGE
# python recognize_faces_image.py --encodings encodings.pickle --image examples/example_01.png 
 
# import the necessary packages
import face_recognition
import argparse
import pickle
import cv2
 
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-e", "--encodings", required=True,
	help="path to serialized db of facial encodings")
ap.add_argument("-i", "--image", required=True,
	help="path to input image")
ap.add_argument("-d", "--detection-method", type=str, default="cnn",
	help="face detection model to use: either `hog` or `cnn`")
args = vars(ap.parse_args())
 
# load the known faces and embeddings
print("[INFO] loading encodings...")
data = pickle.loads(open(args["encodings"], "rb").read())
 
# load the input image and convert it from BGR to RGB
image = cv2.imread(args["image"])
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 
# detect the (x, y)-coordinates of the bounding boxes corresponding
# to each face in the input image, then compute the facial embeddings
# for each face
print("[INFO] recognizing faces...")
boxes = face_recognition.face_locations(rgb,
	model=args["detection_method"])
encodings = face_recognition.face_encodings(rgb, boxes)
 
# initialize the list of names for each face detected
names = []
 
# loop over the facial embeddings
for encoding in encodings:
	# attempt to match each face in the input image to our known
	# encodings
	matches = face_recognition.compare_faces(data["encodings"],
		encoding)
	name = "Unknown"
 
	# check to see if we have found a match
	if True in matches:
		# find the indexes of all matched faces then initialize a
		# dictionary to count the total number of times each face
		# was matched
		matchedIdxs = [i for (i, b) in enumerate(matches) if b]
		counts = {}
 
		# loop over the matched indexes and maintain a count for
		# each recognized face face
		for i in matchedIdxs:
			name = data["names"][i]
			counts[name] = counts.get(name, 0) + 1
 
		# determine the recognized face with the largest number of
		# votes (note: in the event of an unlikely tie Python will
		# select first entry in the dictionary)
		name = max(counts, key=counts.get)
	
	# update the list of names
	names.append(name)
 
# loop over the recognized faces
for ((top, right, bottom, left), name) in zip(boxes, names):
	# draw the predicted face name on the image
	cv2.rectangle(image, (left, top), (right, bottom), (0, 255, 0), 2)
	y = top - 15 if top - 15 > 15 else top + 15
	cv2.putText(image, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
		0.75, (0, 255, 0), 2)
 
# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)

实际效果如下:

Python基于Dlib的人脸识别系统的实现

如果要详细了解细节,请参考:https://www.pyimagesearch.com/2018/06/18/face-recognition-with-opencv-python-and-deep-learning/

到此这篇关于Python基于Dlib的人脸识别系统的实现的文章就介绍到这了,更多相关Python Dlib人脸识别内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python学习笔记(一)(基础入门之环境搭建)
Jun 05 Python
Python基于回溯法子集树模板解决0-1背包问题实例
Sep 02 Python
python 实现一个贴吧图片爬虫的示例
Oct 12 Python
Python+Django搭建自己的blog网站
Mar 13 Python
Python装饰器知识点补充
May 28 Python
Python3中的最大整数和最大浮点数实例
Jul 09 Python
Python 转换文本编码实现解析
Aug 27 Python
Series和DataFrame使用简单入门
Nov 13 Python
python关于倒排列的知识点总结
Oct 13 Python
python实现测试工具(一)——命令行发送get请求
Oct 19 Python
Python基于Opencv识别两张相似图片
Apr 25 Python
DjangoRestFramework 使用 simpleJWT 登陆认证完整记录
Jun 22 Python
python 回溯法模板详解
Feb 26 #Python
python实现信号时域统计特征提取代码
Feb 26 #Python
Python 基于FIR实现Hilbert滤波器求信号包络详解
Feb 26 #Python
python实现逆滤波与维纳滤波示例
Feb 26 #Python
Python全面分析系统的时域特性和频率域特性
Feb 26 #Python
解决pycharm每次打开项目都需要配置解释器和安装库问题
Feb 26 #Python
Python中os模块功能与用法详解
Feb 26 #Python
You might like
PHP 日期时间函数的高级应用技巧
2009/10/10 PHP
php Xdebug 调试扩展的安装与使用.
2010/03/13 PHP
php中二维数组排序问题方法详解
2015/08/28 PHP
PHP实现的字符串匹配算法示例【sunday算法】
2017/12/19 PHP
php使用json-schema模块实现json校验示例
2019/09/28 PHP
laravel model模型处理之修改查询或修改字段时的类型格式案例
2019/10/17 PHP
YII2框架中使用RBAC对模块,控制器,方法的权限控制及规则的使用示例
2020/03/18 PHP
动态加载外部javascript文件的函数代码分享
2011/07/28 Javascript
基于jquery的大众点评,分类导航实现代码
2011/08/23 Javascript
Fixie.js 自动填充内容的插件
2012/06/28 Javascript
jquery数组之存放checkbox全选值示例代码
2013/12/20 Javascript
javascript/jquery获取地址栏url参数的方法
2014/03/05 Javascript
javascript检测两个数组是否相似
2015/05/19 Javascript
JQuery通过AJAX从后台获取信息显示在表格上并支持行选中
2015/09/15 Javascript
使用do...while的方法输入一个月中所有的周日(实例代码)
2016/07/22 Javascript
尝试自己动手用react来写一个分页组件(小结)
2018/02/09 Javascript
Javascript实现一朵从含苞到绽放的玫瑰
2019/03/30 Javascript
vue实现移动端省市区选择
2019/09/27 Javascript
JS函数基本定义与用法示例
2020/01/15 Javascript
Openlayers绘制聚合标注
2020/09/28 Javascript
[00:34]TI7不朽珍藏III——地穴编织者不朽展示
2017/07/15 DOTA
python使用三角迭代计算圆周率PI的方法
2015/03/20 Python
Python RuntimeError: thread.__init__() not called解决方法
2015/04/28 Python
树莓派采用socket方式文件传输(python)
2019/06/22 Python
基于python解线性矩阵方程(numpy中的matrix类)
2019/10/21 Python
Pytorch 实现数据集自定义读取
2020/01/18 Python
tensorflow获取预训练模型某层参数并赋值到当前网络指定层方式
2020/01/24 Python
HTML5+WebSocket实现多文件同时上传的实例
2016/12/29 HTML / CSS
利物浦足球俱乐部官方网上商店:Liverpool FC Official Store
2018/01/13 全球购物
英国时尚配饰、珠宝和服装网站:KJ Beckett
2020/01/23 全球购物
数学检讨书1000字
2014/02/24 职场文书
政治思想表现评语
2014/05/04 职场文书
文明和谐家庭事迹材料
2014/05/18 职场文书
关于读书的演讲稿1000字
2014/08/27 职场文书
作风大整顿心得体会
2014/09/10 职场文书
博士论文答辩开场白
2015/06/01 职场文书