【二:dlib人脸检测】python3.5实现人脸检测

本文介绍如何使用dlib包进行人脸检测,通过Python代码演示了使用dlib自带的人脸检测器进行人脸检测的过程,包括读取图片、检测人脸、绘制矩形框并展示结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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,试验效果图:

采样1

采样次数为2,试验效果图:

采样2

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值