您的位置:首页 > 编程语言 > Python开发

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

2019-01-24 21:54 836 查看

1. 引言

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

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

图 1 动态实时检测效果图

 

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

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

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

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

 

2. 代码实现

  主要分为三个部分:

 

2.1 摄像头调用

  Python 中利用 OpenCv 调用摄像头的一个例子 https://github.com/coneypo/Dlib_face_cut/blob/master/how_to_use_camera.py :

# OpenCv 调用摄像头
# 默认调用笔记本摄像头

# Author:   coneypo
# Blog:     http://www.cnblogs.com/AdaminXie
# GitHub:   https://github.com/coneypo/Dlib_face_recognition_from_camera
# Mail:     coneypo@foxmail.com

import cv2

cap = cv2.VideoCapture(0)

# cap.set(propId, value)
# 设置视频参数: propId - 设置的视频参数, value - 设置的参数值
cap.set(3, 480)

# cap.isOpened() 返回 true/false, 检查摄像头初始化是否成功
print(cap.isOpened())

# cap.read()
"""
返回两个值
先返回一个布尔值, 如果视频读取正确, 则为 True, 如果错误, 则为 False;
也可用来判断是否到视频末尾;

再返回一个值, 为每一帧的图像, 该值是一个三维矩阵;

通用接收方法为:
ret,frame = cap.read();
ret: 布尔值;
frame: 图像的三维矩阵;
这样 ret 存储布尔值, frame 存储图像;

若使用一个变量来接收两个值, 如:
frame = cap.read()
则 frame 为一个元组, 原来使用 frame 处需更改为 frame[1]
"""

while cap.isOpened():
ret_flag, img_camera = cap.read()
cv2.imshow("camera", img_camera)

# 每帧数据延时 1ms, 延时为0, 读取的是静态帧
k = cv2.waitKey(1)

# 按下 's' 保存截图
if k == ord('s'):
cv2.imwrite("test.jpg", img_camera)

# 按下 'q' 退出
if k == ord('q'):
break

# 释放所有摄像头
cap.release()

# 删除建立的所有窗口
cv2.destroyAllWindows()

 

2.2 人脸检测

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

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

# created at 2017-11-27
# updated at 2018-09-06

# Author:   coneypo
# Dlib:     http://dlib.net/
# Blog:     http://www.cnblogs.com/AdaminXie/
# Github:   https://github.com/coneypo/Dlib_examples

# create object of OpenCv
# use OpenCv to read and show images

import dlib
import cv2

# 使用 Dlib 的正面人脸检测器 frontal_face_detector
detector = dlib.get_frontal_face_detector()

# 图片所在路径
# read image
img = cv2.imread("imgs/faces_2.jpeg")

# 使用 detector 检测器来检测图像中的人脸
# use detector of Dlib to detector faces
faces = detector(img, 1)
print("人脸数 / Faces in all: ", len(faces))

# Traversal every face
for i, d in enumerate(faces):
print("第", i+1, "个人脸的矩形框坐标:",
"left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
cv2.rectangle(img, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)

cv2.namedWindow("img", 2)
cv2.imshow("img", img)
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 in enumerate(faces):
height = d.bottom() - d.top()
width = d.right() - d.left()

# 如果没有超出摄像头边界
if ((d.top()+height) < 480) and ((d.left()+width)<640):
# 填充
for i in range(height):
for j in range(width):
img_rd[i][blank_start + j] = \
img_rd[d.top() + i][d.left() + j]
# 调整图像
blank_start += width

 

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

 

图 4 平铺显示的人脸

 

2.4. 完整源码

  https://github.com/coneypo/Dlib_face_cut/blob/master/faces_from_camera.py:

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

# Author:   coneypo
# Blog:     http://www.cnblogs.com/AdaminXie
# GitHub:   https://github.com/coneypo/Dlib_face_detection_from_camera

import dlib
import cv2
import time
import numpy as np

# 储存截图的目录
path_screenshots = "data/images/screenshots/"

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('data/dlib/shape_predictor_68_face_landmarks.dat')

# 创建 cv2 摄像头对象
cap = cv2.VideoCapture(0)

# cap.set(propId, value)
# 设置视频参数,propId 设置的视频参数,value 设置的参数值
cap.set(3, 960)

# 截图 screenshots 的计数器
cnt = 0

# cap.isOpened() 返回 true/false 检查初始化是否成功
while cap.isOpened():

# cap.read()
# 返回两个值:
#    一个布尔值 true/false,用来判断读取视频是否成功/是否到视频末尾
#    图像对象,图像的三维矩阵
flag, img_rd = cap.read()

# 每帧数据延时 1ms,延时为 0 读取的是静态帧
k = cv2.waitKey(1)

# 取灰度
img_gray = cv2.cvtColor(img_rd, cv2.COLOR_RGB2GRAY)

# 人脸数
faces = detector(img_gray, 0)

# 待会要写的字体
font = cv2.FONT_HERSHEY_SIMPLEX

# 按下 'q' 键退出
if k == ord('q'):
break
else:
if len(faces) != 0:
# 检测到人脸
for kk, d in enumerate(faces):
# 绘制矩形框
cv2.rectangle(img_rd, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 255, 255), 2)

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

# 生成用来显示的图像
img_blank = np.zeros((height, width, 3), np.uint8)

# 记录每次开始写入人脸像素的宽度位置
blank_start = 0
# 如果没有超出摄像头边界
if (d.bottom() < 480) and (d.right() < 640):
for k, d in enumerate(faces):
height = d.bottom() - d.top()
width = d.right() - d.left()

# 如果没有超出摄像头边界
if ((d.top()+height) < 480) and ((d.left()+width)<640):
# 填充
for i in range(height):
for j in range(width):
img_rd[i][blank_start + j] = \
img_rd[d.top() + i][d.left() + j]
# 调整图像
blank_start += width

cv2.putText(img_rd, "Faces in all: " + str(len(faces)), (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)

else:
# 没有检测到人脸
cv2.putText(img_rd, "no face", (20, 350), font, 0.8, (0, 0, 0), 1, cv2.LINE_AA)

# 添加说明
img_rd = cv2.putText(img_rd, "Press 'S': Screen shot", (20, 400), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
img_rd = cv2.putText(img_rd, "Press 'Q': Quit", (20, 450), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)

# 按下 's' 键保存
if k == ord('s'):
cnt += 1
print(path_screenshots + "screenshot" + "_" + str(cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
time.localtime()) + ".jpg")
cv2.imwrite(path_screenshots + "screenshot" + "_" + str(cnt) + "_" + time.strftime("%Y-%m-%d-%H-%M-%S",
time.localtime()) + ".jpg",
img_rd)

cv2.namedWindow("camera", 1)
cv2.imshow("camera", img_rd)

# 释放摄像头
cap.release()

# 删除建立的窗口
cv2.destroyAllWindows()

 

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

  https://www.geek-share.com/detail/2722785201.html

  https://www.geek-share.com/detail/2727754760.html

 

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

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

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: