使用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,試驗效果圖: