使用python dlib包 做人脸检测,官方给出一些例子,本文基于这些例子来做人脸检测。
使用python包dlib自带的人脸检测器,dlib.get_frontal_face_detector(),该方法使用的是方向梯度直方图(Histogram of Oriented Gradient, HOG)和线性分类器、影像金字塔以及滑动窗口。官方给出的解释为:
This face detector is made using the now classic Histogram of Oriented Gradients (HOG) feature combined with a linear classifier, an image pyramid, and sliding window detection scheme. This type of object detector is fairly general and capable of detecting many types of semi-rigid objects in addition to human faces.
# -*-encoding=utf-8-*-
import sys
import dlib
import cv2
detector = dlib.get_frontal_face_detector()
for f in sys.argv[1:]:
img = cv2.imread(f, cv2.IMREAD_COLOR)
dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))
for index, face in enumerate(dets):
print('face {}; left {}; top {}; right {}; bottom {}'.format(index, face.left(), face.top(), face.right(), face.bottom()))
left = face.left()
top = face.top()
right = face.right()
bottom = face.bottom()
cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 3)
cv2.namedWindow(f, cv2.WINDOW_AUTOSIZE)
cv2.imshow(f, img)
k = cv2.waitKey(0)
cv2.destroyAllWindows()
detector = dlib.get_frontal_face_detector()
dets = detector(img, 2)
为库自带的人脸检测器,当然dlib 也举出如何去训练自己的检测器的例子train_object_detector.py。
dlib.get_frontal_face_detector(Python Function, in Classes),返回值是一个矩形,坐标为[(x1,y1)(x2,y2)],可以通过函数的left, top,right, bottom的方法获得其对应的x1,y1,x2,y2.
left:人脸左边距离图片左边界的距离;right:人脸右边距离图片左边界的距离
top:人脸上边距离图片上边界的距离;bottom:人脸下边距离图片上边界的距离
for index, face in enumerate(dets):
pass
enumerate是一个Python的内置方法,用于遍历索引。 index是序号;face是dets中取出的dlib.rectangle类的对象,包含了人脸的区域等信息: left()、top()、right()、bottom()都是dlib.rectangle类的方法,对应矩形四条边的位置,也就是矩形坐标值。
in Classes 表示采样(unsample)次数,次数越多,越精细,时间越长
k = cv2.waitKey(0)
保持一个绘画的窗口一直显示,具体用法见waitKey() 函数的作用
运行命令为python xxx.py 1.jpg
如果是在pycharm ide 中,则只需在Edit Configurations 中的Script parameters项中配置1.jpg即可
试验原始图:
采样次数为1,试验效果图:
采样次数为2,试验效果图: