最近接触到一个很酷的模块 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()
这里本人就不再贴图了! 大家有条件的可以试试