python人脸检测

最近接触到一个很酷的模块 dlib 来看看官方的介绍:
Dlib is a modern C++ toolkit containing machine learning algorithms and tools for creating complex software in C++ to solve real world problems. It is used in both industry and academia in a wide range of domains including robotics, embedded devices, mobile phones, and large high performance computing environments. Dlib's open source licensing allows you to use it in any application, free of charge.

dlib 可以做哪些事情:
1 人脸检测
2 人脸识别
3 人脸特征标记
4 目标追踪

所以本文就来通过一个demo介绍使用dlib 实现通过摄像头实现人脸检测

运行环境

Python 3.4.5
Deepin-15.9.1
dlib 19.16.0
opencv-python 3.4.2.17

如何读取摄像头数据

读取摄像头数据需要依赖于opencv 来实现
demo 大概如下:

import cv2
# 0 代表笔记本的摄像头,(不需要打开摄像头,cv会自动打开摄像头)
video = cv2.VideoCapture(0)
while 1:
	 # read返回两个值 一个 是否读取成功  一个是每一帧的视频数据
     stream, frame = video.read()
     if not stream:
     	break
     # 将读取到的视频显示出来
     cv2.imshow("video", frame)
     # waitKey 可以监听键盘输入,当你把光标点击到视频的时候按下键盘就能获取到输入了哪个键,因此我这里做了监听 如果按下 q 键 则退出
	 key = cv2.waitKey(2)
     if key == ord('q'):
          break
          
 video.release()
 cv2.destroyAllWindows()

如何检测人脸

这时候就需要用到dlib了
大家可以看看官方提供的 example:https://github.com/davisking/dlib/blob/master/python_examples/face_detector.py

以下是个人写的完整的demo

cv2_read_camera0.py

import dlib
import cv2

video = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()

def read_camera0():
    """
    读取电脑摄像头的视频(不需要打开摄像头,cv会自动打开摄像头)
    """
    while 1:
        stream, frame = video.read()
        if stream:
            yield frame
        else:
            print("Cannot Read Camera0")
            break

def show_camera_faces():
    """
    读取摄像头数据,显示出来加上人脸检测
    """
    frames = read_camera0()
    for image in frames:
        rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        detect = detector(rgb_image, 1)

        for i, d in enumerate(detect):
            x1, y1, x2, y2, w, h = d.left(), d.top(), d.right() + 1, d.bottom() + 1, d.width(), d.height()
            cv2.rectangle(image, (x1, y1), (x2, y2), (255, 0, 0), 2)
        cv2.imshow("video", image)
        key = cv2.waitKey(2)
        print(key)
        if key == ord('q'):
            break

    video.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    show_camera_faces()

这里本人就不再贴图了! 大家有条件的可以试试

在这里插入图片描述

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值