1. 引言
在某些场景下,我们不仅需要进行实时人脸检测追踪,还要进行再加工;这里进行摄像头实时人脸检测,并对于实时检测的人脸进行初步提取;
单个/多个人脸检测,并依次在摄像头窗口,实时平铺显示检测到的人脸;
图 1 动态实时检测效果图
检测到的人脸矩形图像,会依次平铺显示在摄像头的左上方;
当多个人脸时候,也能够依次铺开显示;
左上角窗口的大小会根据捕获到的人脸大小实时变化;
图 2 单个/多个人脸情况下摄像头识别显示结果
2. 代码实现
主要分为三个部分:
摄像头调用,利用 OpenCv 里面的cv2.VideoCapture();
人脸检测 / Face detect,这里利用开源的 Dlib 框架,Dlib 中人脸检测具体可以参考/AdaminXie/p/7905888.html;
2.1 摄像头调用
1 #OpenCv 调用摄像头
2 #默认调用笔记本摄像头
3
4 #Author: coneypo
5 #Blog: /AdaminXie
6 #GitHub: /coneypo/Dlib_face_recognition_from_camera
7 #Mail: coneypo@
8
9 importcv210
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 whilecap.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 进行人脸检测的例子:
1 #created at -11-27
2 #updated at -09-06
3
4 #Author: coneypo
5 #Dlib: /
6 #Blog: /AdaminXie/
7 #Github: /coneypo/Dlib_examples
8
9 #create object of OpenCv
10 #use OpenCv to read and show images
11
12 importdlib13 importcv214
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 inenumerate(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);
所以进行图像裁剪填充这块的代码如下(注意超出 640x480 区域时的处理):
#记录每次开始写入人脸像素的宽度位置
blank_start =0#如果没有超出摄像头边界
if (d.bottom() < 480) and (d.right() < 640):for k, d inenumerate(faces):
height= d.bottom() -d.top()
width= d.right() -d.left()#如果没有超出摄像头边界
if ((d.top()+height) < 480) and ((d.left()+width)<640):#填充
for i inrange(height):for j inrange(width):
img_rd[i][blank_start+ j] =\
img_rd[d.top()+ i][d.left() +j]#调整图像
blank_start += width
记得要更新 blank_start 的坐标,达到依次平铺的效果:
图 4 平铺显示的人脸
2.4. 完整源码
1 #调用摄像头实时单个/多个人脸检测,并依次在摄像头窗口,实时平铺显示检测到的人脸;
2
3 #Author: coneypo
4 #Blog: /AdaminXie
5 #GitHub: /coneypo/Dlib_face_detection_from_camera
6
7 importdlib8 importcv29 importtime10 importnumpy as np11
12 #储存截图的目录
13 path_screenshots = "data/images/screenshots/"
14
15 detector =dlib.get_frontal_face_detector()16 predictor = dlib.shape_predictor('data/dlib/shape_predictor_68_face_landmarks.dat')17
18 #创建 cv2 摄像头对象
19 cap =cv2.VideoCapture(0)20
21 #cap.set(propId, value)
22 #设置视频参数,propId 设置的视频参数,value 设置的参数值
23 cap.set(3, 960)24
25 #截图 screenshots 的计数器
26 cnt =027
28 #cap.isOpened() 返回 true/false 检查初始化是否成功
29 whilecap.isOpened():30
31 #cap.read()
32 #返回两个值:
33 #一个布尔值 true/false,用来判断读取视频是否成功/是否到视频末尾
34 #图像对象,图像的三维矩阵
35 flag, img_rd =cap.read()36
37 #每帧数据延时 1ms,延时为 0 读取的是静态帧
38 k = cv2.waitKey(1)39
40 #取灰度
41 img_gray =cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)42
43 #人脸数
44 faces =detector(img_gray, 0)45
46 #待会要写的字体
47 font =cv2.FONT_HERSHEY_SIMPLEX48
49 #按下 'q' 键退出
50 if k == ord('q'):51 break
52 else:53 if len(faces) !=0:54 #检测到人脸
55 for kk, d inenumerate(faces):56 #绘制矩形框
57 cv2.rectangle(img_rd, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)58
59 height = d.bottom() -d.top()60 width = d.right() -d.left()61
62 #生成用来显示的图像
63 img_blank = np.zeros((height, width, 3), np.uint8)64
65 #记录每次开始写入人脸像素的宽度位置
66 blank_start =067 #如果没有超出摄像头边界
68 if (d.bottom() < 480) and (d.right() < 640):69 for k, d inenumerate(faces):70 height = d.bottom() -d.top()71 width = d.right() -d.left()72
73 #如果没有超出摄像头边界
74 if ((d.top()+height) < 480) and ((d.left()+width)<640):75 #填充
76 for i inrange(height):77 for j inrange(width):78 img_rd[i][blank_start + j] =\79 img_rd[d.top() + i][d.left() +j]80 #调整图像
81 blank_start +=width82
83 cv2.putText(img_rd, "Faces in all:" + str(len(faces)), (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)84
85 else:86 #没有检测到人脸
87 cv2.putText(img_rd, "no face", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)88
89 #添加说明
90 img_rd = cv2.putText(img_rd, "Press 'S': Screen shot", (20, 400), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)91 img_rd = cv2.putText(img_rd, "Press 'Q': Quit", (20, 450), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)92
93 #按下 's' 键保存
94 if k == ord('s'):95 cnt += 1
96 print(path_screenshots + "screenshot" + "_" + str(cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",97 time.localtime()) + ".jpg")98 cv2.imwrite(path_screenshots + "screenshot" + "_" + str(cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",99 time.localtime()) + ".jpg",100 img_rd)101
102 cv2.namedWindow("camera", 1)103 cv2.imshow("camera", img_rd)104
105 #释放摄像头
106 cap.release()107
108 #删除建立的窗口
109 cv2.destroyAllWindows()
这个代码就是把之前做的人脸检测,图像拼接几个结合起来,代码量也很少,只有100行,如有问题可以参考之前博客:
# 如有问题请留言或者联系邮箱coneypo@,商业合作勿扰