dlib 人脸检测

采用经典的梯度方向直方图(HOG特征)提取+线性分类器+图像金字塔+滑动窗口的人脸检测方法。该方法速度快,只能检测80*80或更大的人脸,但可以通过图像上采样来检测更小的人脸。与OpenCV的人脸检测相比,召回率更高,误检率更低,且人脸框更准确,检测速度同样很快。

代码实现:

import cv2
import dlib

detector = dlib.get_frontal_face_detector()       #获取dlib正脸检测器

img = cv2.imread("a.jpg")        #opencv读取图片,并显示

img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)      #灰度处理

rects = detector(img_gray, 0)      #0次上采样,dlib的人脸检测器只能检测80*80和更大的人脸,若需要检测比它小的人脸,需对图像上采样
print("The number of faces: {}".format(len(rects)))       #识别到的人脸个数
for rect in rects:
    #cv2.rectangle()画出矩形,参数1:图像,参数2:矩形左上角坐标,参数3:矩形右下角坐标,参数4:画线对应的rgb颜色,参数5:线的宽度
    cv2.rectangle(img, (rect.left(),rect.top()), (rect.right(),rect.bottom()), (0,0,255),2)
    
cv2.namedWindow("img", 2)      #图片窗口可调节大小
cv2.imshow("img", img)        #显示图像
cv2.waitKey(0)       #等待按键,随后退出

运行结果:

The number of faces: 1

猜你喜欢

转载自blog.csdn.net/weixin_40277254/article/details/82113953