python 3利用Dlib 19.7实现摄像头人脸检测特征点标定


Posted in Python onFebruary 26, 2018

Python 3 利用 Dlib 19.7 实现摄像头人脸检测特征点标定

0.引言

利用python开发,借助Dlib库捕获摄像头中的人脸,进行实时特征点标定;

python 3利用Dlib 19.7实现摄像头人脸检测特征点标定

图1 工程效果示例(gif)

python 3利用Dlib 19.7实现摄像头人脸检测特征点标定

图2 工程效果示例(静态图片)

(实现比较简单,代码量也比较少,适合入门或者兴趣学习。)

1.开发环境

python:

3.6.3

dlib:

  19.7

OpenCv, numpy

import dlib     # 人脸识别的库dlib
import numpy as np # 数据处理的库numpy
import cv2     # 图像处理的库OpenCv

2.源码介绍

其实实现很简单,主要分为两个部分:摄像头调用+人脸特征点标定

2.1 摄像头调用

介绍下opencv中摄像头的调用方法;

利用 cap = cv2.VideoCapture(0) 创建一个对象;

(具体可以参考官方文档)

# 2018-2-26
# By TimeStamp
# cnblogs: http://www.cnblogs.com/AdaminXie

"""
cv2.VideoCapture(), 创建cv2摄像头对象/ open the default camera

  Python: cv2.VideoCapture() → <VideoCapture object>

  Python: cv2.VideoCapture(filename) → <VideoCapture object>  
  filename ? name of the opened video file (eg. video.avi) or image sequence (eg. img_%02d.jpg, which will read samples like img_00.jpg, img_01.jpg, img_02.jpg, ...)

  Python: cv2.VideoCapture(device) → <VideoCapture object>
  device ? id of the opened video capturing device (i.e. a camera index). If there is a single camera connected, just pass 0.

"""
cap = cv2.VideoCapture(0)


"""
cv2.VideoCapture.set(propId, value),设置视频参数;

  propId:
  CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.
  CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
  CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file: 0 - start of the film, 1 - end of the film.
  CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
  CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
  CV_CAP_PROP_FPS Frame rate.
  CV_CAP_PROP_FOURCC 4-character code of codec.
  CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
  CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
  CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
  CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
  CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
  CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
  CV_CAP_PROP_HUE Hue of the image (only for cameras).
  CV_CAP_PROP_GAIN Gain of the image (only for cameras).
  CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
  CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
  CV_CAP_PROP_WHITE_BALANCE_U The U value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
  CV_CAP_PROP_WHITE_BALANCE_V The V value of the whitebalance setting (note: only supported by DC1394 v 2.x backend currently)
  CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
  CV_CAP_PROP_ISO_SPEED The ISO speed of the camera (note: only supported by DC1394 v 2.x backend currently)
  CV_CAP_PROP_BUFFERSIZE Amount of frames stored in internal buffer memory (note: only supported by DC1394 v 2.x backend currently)
  
  value: 设置的参数值/ Value of the property
"""
cap.set(3, 480)

"""
cv2.VideoCapture.isOpened(), 检查摄像头初始化是否成功 / check if we succeeded
返回true或false
"""
cap.isOpened()

""" 
cv2.VideoCapture.read([imgage]) -> retval,image, 读取视频 / Grabs, decodes and returns the next video frame
返回两个值:
  一个是布尔值true/false,用来判断读取视频是否成功/是否到视频末尾
  图像对象,图像的三维矩阵
"""
flag, im_rd = cap.read()

2.2 人脸特征点标定

调用预测器“shape_predictor_68_face_landmarks.dat”进行68点标定,这是dlib训练好的模型,可以直接调用进行人脸68个人脸特征点的标定;

具体可以参考我的另一篇博客(python3利用Dlib19.7实现人脸68个特征点标定); 

2.3 源码

实现的方法比较简单:

利用 cv2.VideoCapture() 创建摄像头对象,然后利用 flag, im_rd = cv2.VideoCapture.read() 读取摄像头视频,im_rd就是视频中的一帧帧图像;

然后就类似于单张图像进行人脸检测,对这一帧帧的图像im_rd利用dlib进行特征点标定,然后绘制特征点;

你可以按下s键来获取当前截图,或者按下q键来退出摄像头;

# 2018-2-26

# By TimeStamp
# cnblogs: http://www.cnblogs.com/AdaminXie
# github: https://github.com/coneypo/Dlib_face_detection_from_camera

import dlib           #人脸识别的库dlib
import numpy as np       #数据处理的库numpy
import cv2           #图像处理的库OpenCv

# dlib预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

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

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

# 截图screenshoot的计数器
cnt = 0

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

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

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

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

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

  #print(len(rects))

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

  # 标68个点
  if(len(rects)!=0):
    # 检测到人脸
    for i in range(len(rects)):
      landmarks = np.matrix([[p.x, p.y] for p in predictor(im_rd, rects[i]).parts()])

      for idx, point in enumerate(landmarks):
        # 68点的坐标
        pos = (point[0, 0], point[0, 1])

        # 利用cv2.circle给每个特征点画一个圈,共68个
        cv2.circle(im_rd, pos, 2, color=(0, 255, 0))

        # 利用cv2.putText输出1-68
        cv2.putText(im_rd, str(idx + 1), pos, font, 0.2, (0, 0, 255), 1, cv2.LINE_AA)
    cv2.putText(im_rd, "faces: "+str(len(rects)), (20,50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)
  else:
    # 没有检测到人脸
    cv2.putText(im_rd, "no face", (20, 50), font, 1, (0, 0, 255), 1, cv2.LINE_AA)

  # 添加说明
  im_rd = cv2.putText(im_rd, "s: screenshot", (20, 400), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)
  im_rd = cv2.putText(im_rd, "q: quit", (20, 450), font, 0.8, (255, 255, 255), 1, cv2.LINE_AA)

  # 按下s键保存
  if (k == ord('s')):
    cnt+=1
    cv2.imwrite("screenshoot"+str(cnt)+".jpg", im_rd)

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

  # 窗口显示
  cv2.imshow("camera", im_rd)

# 释放摄像头
cap.release()

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

如果对您有帮助,欢迎在GitHub上star本项目。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python3.x和Python2.x的区别介绍
Feb 12 Python
编写Python脚本来获取Google搜索结果的示例
May 04 Python
使用httplib模块来制作Python下HTTP客户端的方法
Jun 19 Python
解决Python传递中文参数的问题
Aug 04 Python
Python随机数用法实例详解【基于random模块】
Apr 18 Python
python对常见数据类型的遍历解析
Aug 27 Python
使用Python实现 学生学籍管理系统
Nov 26 Python
python中利用matplotlib读取灰度图的例子
Dec 07 Python
python变量的作用域是什么
May 26 Python
Python用K-means聚类算法进行客户分群的实现
Aug 23 Python
TensorFlow的环境配置与安装方法
Feb 20 Python
10个顶级Python实用库推荐
Mar 04 Python
python3利用Dlib19.7实现人脸68个特征点标定
Feb 26 #Python
python微信跳一跳系列之棋子定位颜色识别
Feb 26 #Python
python微信跳一跳系列之棋子定位像素遍历
Feb 26 #Python
python3.6+opencv3.4实现鼠标交互查看图片像素
Feb 26 #Python
python微信跳一跳系列之自动计算跳一跳距离
Feb 26 #Python
python微信跳一跳系列之色块轮廓定位棋盘
Feb 26 #Python
tensorflow入门之训练简单的神经网络方法
Feb 26 #Python
You might like
《心理测量者3》剧场版动画预告
2020/03/02 日漫
PHP json_decode函数详细解析
2014/02/17 PHP
php导入大量数据到mysql性能优化技巧
2014/12/29 PHP
CI框架常用函数封装实例
2016/11/21 PHP
PHP中使用jQuery+Ajax实现分页查询多功能操作(示例讲解)
2017/09/17 PHP
设置jsf的选择框h:selectOneMenu为不可编辑状态的方法
2014/01/07 Javascript
JS函数重载的解决方案
2014/05/13 Javascript
escape编码与unescape解码汉字出现乱码的解决方法
2014/07/02 Javascript
js生成的验证码的实现与技术分析
2014/09/17 Javascript
js拆分字符串并将分割的数据放到数组中的方法
2015/05/06 Javascript
jQuery实现强制cookie过期方法汇总
2015/05/22 Javascript
jQuery实现Email邮箱地址自动补全功能代码
2015/11/03 Javascript
Bootstrap每天必学之折叠
2016/04/12 Javascript
window.open不被拦截的简单实现代码(推荐)
2016/08/04 Javascript
AngularJS 使用ng-repeat报错 [ngRepeat:dupes]
2017/01/19 Javascript
node.js中fs.stat与fs.fstat的区别详解
2017/06/01 Javascript
详解升级react-router 4 踩坑指南
2017/08/14 Javascript
jquery+css实现下拉列表功能
2017/09/03 jQuery
详解Vue.js组件可复用性的混合(mixin)方式和自定义指令
2017/09/06 Javascript
jQuery实现的网站banner图片无缝轮播效果完整实例
2019/01/28 jQuery
vue-cli配置全局sass、less变量的方法
2019/06/06 Javascript
JS 设计模式之:工厂模式定义与实现方法浅析
2020/05/06 Javascript
[09:40]DAC2018 4.5 SOLO赛 MidOne vs Miracle
2018/04/06 DOTA
python双向链表实现实例代码
2013/11/21 Python
Python 列表(List)操作方法详解
2014/03/11 Python
django mysql数据库及图片上传接口详解
2019/07/18 Python
python3 map函数和filter函数详解
2019/08/26 Python
AmazeUI中模态框的实现
2020/08/19 HTML / CSS
交通安全教育制度
2014/02/02 职场文书
中学生寄语大全
2014/04/03 职场文书
幼儿生日活动方案
2014/08/27 职场文书
离婚协议书范本2014
2014/10/27 职场文书
有关浪费资源的建议书
2015/09/14 职场文书
原生JS实现飞机大战小游戏
2021/06/09 Javascript
Smart 2 车辆代号 HC11 全新谍照曝光
2022/04/21 数码科技
Linux中各个目录的作用与内容
2022/06/28 Servers