温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么实现人脸检测

发布时间:2021-07-05 17:23:37 来源:亿速云 阅读:156 作者:Leah 栏目:编程语言

Python中怎么实现人脸检测,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

首先需要安装这些包,以Ubuntu为例:

$ sudo apt-get install build-essential cmake  $ sudo apt-get install libgtk-3-dev  $ sudo apt-get install libboost-all-dev

我们的程序中还用到numpy,opencv,所以也需要安装这些库:

$ pip install numpy  $ pip install scipy  $ pip install opencv-python  $ pip install dlib

人脸检测基于事先训练好的模型数据,从这里可以下到模型数据

http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2

下载到本地路径后解压,记下解压后的文件路径,程序中会用到。

dlib的人脸特征点

上面下载的模型数据是用来估计人脸上68个特征点(x, y)的坐标位置,这68个坐标点的位置如下图所示:

Python中怎么实现人脸检测

我们的程序将包含两个步骤:

***步,在照片中检测人脸的区域

第二部,在检测到的人脸区域中,进一步检测器官(眼睛、鼻子、嘴巴、下巴、眉毛)

人脸检测代码

我们先来定义几个工具函数:

def rect_to_bb(rect):      x = rect.left()      y = rect.top()      w = rect.right() - x       h = rect.bottom() - y          return (x, y, w, h)

这个函数里的rect是dlib脸部区域检测的输出。这里将rect转换成一个序列,序列的内容是矩形区域的边界信息。

def shape_to_np(shape, dtype="int"):      coords = np.zeros((68, 2), dtype=dtype)          for i in range(0, 68):              coords[i] = (shape.part(i).x, shape.part(i).y)         return coords

这个函数里的shape是dlib脸部特征检测的输出,一个shape里包含了前面说到的脸部特征的68个点。这个函数将shape转换成Numpy array,为方便后续处理。

def  resize(image, width=1200):      r = width * 1.0 / image.shape[1]      dim = (width, int(image.shape[0] * r))       resized = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)          return resized

这个函数里的image就是我们要检测的图片。在人脸检测程序的***,我们会显示检测的结果图片来验证,这里做resize是为了避免图片过大,超出屏幕范围。

接下来,开始我们的主程序部分

import sys import numpy as np  import dlib import cv2   if len(sys.argv) < 2:          print "Usage: %s <image file>" % sys.argv[0]      sys.exit(1)  image_file = sys.argv[1]  detector = dlib.get_frontal_face_detector()  predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

我们从sys.argv[1]参数中读取要检测人脸的图片,接下来初始化人脸区域检测的detector和人脸特征检测的predictor。shape_predictor中的参数就是我们之前解压后的文件的路径。

image = cv2.imread(image_file)  image = resize(image, width=1200)  gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  rects = detector(gray, 1)

在检测特征区域前,我们先要检测人脸区域。这段代码调用opencv加载图片,resize到合适的大小,转成灰度图,***用detector检测脸部区域。因为一张照片可能包含多张脸,所以这里得到的是一个包含多张脸的信息的数组rects。

for (i, rect) in enumerate(rects):      shape = predictor(gray, rect)      shape = shape_to_np(shape)      (x, y, w, h) = rect_to_bb(rect)      cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)      cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)      for (x, y) in shape:              cv2.circle(image, (x, y), 2, (0, 0, 255), -1)   cv2.imshow("Output", image)  cv2.waitKey(0)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI