python dlib人脸检测

安装dlib

pip install dlib

代码

import cv2
import dlib

capture_index = 0

def img2gray(img):
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 使用dlib自带的frontal_face_detector作为我们的特征提取器
def main():
    detector = dlib.get_frontal_face_detector()
    # 打开摄像头
    cap = cv2.VideoCapture(capture_index)
    # 开始检测
    while True:
        success, img = cap.read()
        # 转化为灰度图
        gray_img = img2gray(img)
        # 检测
        dets = detector(img, 1)
        # 这个也可以
        # dets = detector(gray_img, 1)

        print("找到人脸%d个" %len(dets))
        cv2.namedWindow("image")
        # 找到人脸坐标
        face_rect = []
        # for i,d in enumerate(dets):
        for d in dets:
            face = []
            y1 = d.top() if d.top() > 0 else 0
            x1 = d.left() if d.left() > 0 else 0
            x2 = d.right() if d.right() > 0 else 0
            y2 = d.bottom() if d.bottom() > 0 else 0
            face.append(x1)
            face.append(y1)
            face.append(x2)
            face.append(y2)
            face_rect.append(face)

        # 画框
        for rect in face_rect:
            cv2.rectangle(img,(rect[0],rect[1]),(rect[2],rect[3]), (0,255,255))
        # 竖直翻转一下并显示
        cv2.imshow("image", cv2.flip(img,1))
        cv2.waitKey(1)
    
    return 0

if __name__ == "__main__":
    main()

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值