Python 3 利用 Dlib 实现摄像头实时人脸检测和平铺显示

 

1. 引言

  在某些场景下,我们不仅需要进行实时人脸检测追踪,还要进行再加工;这里进行摄像头实时人脸检测,并对于实时检测的人脸进行初步提取;

  单个/多个人脸检测,并依次在摄像头窗口,实时平铺显示检测到的人脸;

图 1 动态实时检测效果图

 

  检测到的人脸矩形图像,会依次 平铺显示 在摄像头的左上方;

  当多个人脸时候,也能够依次铺开显示;

  左上角窗口的大小会根据捕获到的人脸大小实时变化;

图 2 单个/多个人脸情况下摄像头识别显示结果

 

2. 代码实现

  主要分为三个部分:

 

2.1 摄像头调用

  Python 中利用 OpenCv 调用摄像头的一个例子 how_to_use_camera.py :

 1 # OpenCv 调用摄像头
 2 # 默认调用笔记本摄像头
 3 
 4 # Author:   coneypo
 5 # Blog:     http://www.cnblogs.com/AdaminXie
 6 # GitHub:   https://github.com/coneypo/Dlib_face_cut
 7 # Mail:     coneypo@foxmail.com
 8 
 9 import cv2
10 
11 cap = cv2.VideoCapture(0)
12 
13 # cap.set(propId, value)
14 # 设置视频参数: propId - 设置的视频参数, value - 设置的参数值
15 cap.set(3, 480)
16 
17 # cap.isOpened() 返回 true/false, 检查摄像头初始化是否成功
18 print(cap.isOpened())
19 
20 # cap.read()
21 """ 
22 返回两个值
23     先返回一个布尔值, 如果视频读取正确, 则为 True, 如果错误, 则为 False; 
24     也可用来判断是否到视频末尾;
25     
26     再返回一个值, 为每一帧的图像, 该值是一个三维矩阵;
27     
28     通用接收方法为: 
29         ret,frame = cap.read();
30         ret: 布尔值;
31         frame: 图像的三维矩阵;
32         这样 ret 存储布尔值, frame 存储图像;
33         
34         若使用一个变量来接收两个值, 如:
35             frame = cap.read()
36         则 frame 为一个元组, 原来使用 frame 处需更改为 frame[1]
37 """
38 
39 while cap.isOpened():
40     ret_flag, img_camera = cap.read()
41     cv2.imshow("camera", img_camera)
42 
43     # 每帧数据延时 1ms, 延时为0, 读取的是静态帧
44     k = cv2.waitKey(1)
45 
46     # 按下 's' 保存截图
47     if k == ord('s'):
48         cv2.imwrite("test.jpg", img_camera)
49 
50     # 按下 'q' 退出
51     if k == ord('q'):
52         break
53 
54 # 释放所有摄像头
55 cap.release()
56 
57 # 删除建立的所有窗口
58 cv2.destroyAllWindows()

 

2.2 人脸检测

  利用 Dlib 正向人脸检测器, dlib.get_frontal_face_detector()

  对于本地人脸图像文件,一个利用 Dlib 进行人脸检测的例子:

  face_detector_v2_use_opencv.py :

 1 # created at 2017-11-27
 2 # updated at 2018-09-06
 3 
 4 # Author:   coneypo
 5 # Dlib:     http://dlib.net/
 6 # Blog:     http://www.cnblogs.com/AdaminXie/
 7 # Github:   https://github.com/coneypo/Dlib_examples
 8 
 9 # create object of OpenCv
10 # use OpenCv to read and show images
11 
12 import dlib
13 import cv2
14 
15 # 使用 Dlib 的正面人脸检测器 frontal_face_detector
16 detector = dlib.get_frontal_face_detector()
17 
18 # 图片所在路径
19 # read image
20 img = cv2.imread("imgs/faces_2.jpeg")
21 
22 # 使用 detector 检测器来检测图像中的人脸
23 # use detector of Dlib to detector faces
24 faces = detector(img, 1)
25 print("人脸数 / Faces in all: ", len(faces))
26 
27 # Traversal every face
28 for i, d in enumerate(faces):
29     print("", i+1, "个人脸的矩形框坐标:",
30           "left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
31     cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)
32 
33 cv2.namedWindow("img", 2)
34 cv2.imshow("img", img)
35 cv2.waitKey(0)

 

图 3 参数 d.top(), d.right(), d.left(), d.bottom() 位置坐标说明

 

2.3 图像裁剪

  如果想访问图像的某点像素,对于 opencv 对象可以利用索引 img [height] [width]

    存储像素其实是一个三维数组,先 高度 height,然后 宽度 width;

    返回的是一个颜色数组( 0-255,0-255,0-255 ),按照( B, G, R )的顺序;

    比如 蓝色 就是(255,0,0),红色 是(0,0,255);

  所以要做的就是对于检测到的人脸,要依次平铺填充到摄像头显示的实时帧 img_rd 中;

  所以进行图像裁剪填充这块的代码如下(注意要防止截切平铺的图像不能超出 640x480 ):

# 检测到人脸
if len(faces) != 0:
    # 记录每次开始写入人脸像素的宽度位置
    faces_start_width = 0

    for face in faces:
        # 绘制矩形框
        cv2.rectangle(img_rd, tuple([face.left(), face.top()]), tuple([face.right(), face.bottom()]),
                      (0, 255, 255), 2)

        height = face.bottom() - face.top()
        width = face.right() - face.left()

        ### 进行人脸裁减 ###
        # 如果没有超出摄像头边界
        if (face.bottom() < 480) and (face.right() < 640) and \
                ((face.top() + height) < 480) and ((face.left() + width) < 640):
            # 填充
            for i in range(height):
                for j in range(width):
                    img_rd[i][faces_start_width + j] = \
                        img_rd[face.top() + i][face.left() + j]

        # 更新 faces_start_width 的坐标
        faces_start_width += width

 

   记得要更新 faces_start_width 的坐标,达到依次平铺的效果:

 

 

图 4 平铺显示的人脸

 

2.4. 完整源码

  faces_from_camera.py:

 1 # 调用摄像头实时单个/多个人脸检测,并依次在摄像头窗口,实时平铺显示检测到的人脸;
 2 
 3 # Author:   coneypo
 4 # Blog:     http://www.cnblogs.com/AdaminXie
 5 # GitHub:   https://github.com/coneypo/Dlib_face_cut
 6 
 7 import dlib
 8 import cv2
 9 import time
10 
11 # 储存截图的目录
12 path_screenshots = "data/images/screenshots/"
13 
14 detector = dlib.get_frontal_face_detector()
15 predictor = dlib.shape_predictor('data/dlib/shape_predictor_68_face_landmarks.dat')
16 
17 # 创建 cv2 摄像头对象
18 cap = cv2.VideoCapture(0)
19 
20 # 设置视频参数,propId 设置的视频参数,value 设置的参数值
21 cap.set(3, 960)
22 
23 # 截图 screenshots 的计数器
24 ss_cnt = 0
25 
26 while cap.isOpened():
27     flag, img_rd = cap.read()
28 
29     # 每帧数据延时 1ms,延时为 0 读取的是静态帧
30     k = cv2.waitKey(1)
31 
32     # 取灰度
33     img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)
34 
35     # 人脸数
36     faces = detector(img_gray, 0)
37 
38     # 待会要写的字体
39     font = cv2.FONT_HERSHEY_SIMPLEX
40 
41     # 按下 'q' 键退出
42     if k == ord('q'):
43         break
44     else:
45         # 检测到人脸
46         if len(faces) != 0:
47             # 记录每次开始写入人脸像素的宽度位置
48             faces_start_width = 0
49 
50             for face in faces:
51                 # 绘制矩形框
52                 cv2.rectangle(img_rd, tuple([face.left(), face.top()]), tuple([face.right(), face.bottom()]),
53                               (0, 255, 255), 2)
54 
55                 height = face.bottom() - face.top()
56                 width = face.right() - face.left()
57 
58                 ### 进行人脸裁减 ###
59                 # 如果没有超出摄像头边界
60                 if (face.bottom() < 480) and (face.right() < 640) and \
61                         ((face.top() + height) < 480) and ((face.left() + width) < 640):
62                     # 填充
63                     for i in range(height):
64                         for j in range(width):
65                             img_rd[i][faces_start_width + j] = \
66                                 img_rd[face.top() + i][face.left() + j]
67 
68                 # 更新 faces_start_width 的坐标
69                 faces_start_width += width
70 
71             cv2.putText(img_rd, "Faces in all: " + str(len(faces)), (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
72 
73         else:
74             # 没有检测到人脸
75             cv2.putText(img_rd, "no face", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)
76 
77         # 添加说明
78         img_rd = cv2.putText(img_rd, "Press 'S': Screen shot", (20, 400), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
79         img_rd = cv2.putText(img_rd, "Press 'Q': Quit", (20, 450), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
80 
81     # 按下 's' 键保存
82     if k == ord('s'):
83         ss_cnt += 1
84         print(path_screenshots + "screenshot" + "_" + str(ss_cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
85                                                                                         time.localtime()) + ".jpg")
86         cv2.imwrite(path_screenshots + "screenshot" + "_" + str(ss_cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
87                                                                                               time.localtime()) + ".jpg",
88                     img_rd)
89 
90     cv2.namedWindow("camera", 1)
91     cv2.imshow("camera", img_rd)
92 
93 # 释放摄像头
94 cap.release()
95 
96 # 删除建立的窗口
97 cv2.destroyAllWindows()

 

这个代码就是把之前做的人脸检测,图像拼接几个结合起来,代码量也很少,只有100行,如有问题可以参考之前博客:

  Python 3 利用 Dlib 进行人脸检测

  Python 3 利用 Dlib 实现人脸检测和剪切

 

人脸检测对于机器性能占用不高,但是如果要进行实时的图像裁剪拼接,计算量可能比较大,所以可能会出现卡顿; 

 

# 请尊重他人劳动成果,转载或者使用源码请注明出处:http://www.cnblogs.com/AdaminXie

# 如果对您有帮助,欢迎在 GitHub 上 Star 支持下: https://github.com/coneypo/Dlib_face_cut

# 如有问题请留言或者联系邮箱 coneypo@foxmail.com,商业合作勿扰

posted @ 2019-01-24 21:54  coneypo  阅读(5236)  评论(0编辑  收藏  举报