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 相关文章推荐
Python中.py文件打包成exe可执行文件详解
Mar 22 Python
Python实现压缩和解压缩ZIP文件的方法分析
Sep 28 Python
python生成excel的实例代码
Nov 08 Python
python使用turtle绘制分形树
Jun 22 Python
Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例
Jan 23 Python
Python如何获得百度统计API的数据并发送邮件示例代码
Jan 27 Python
详解Python3中ceil()函数用法
Feb 19 Python
Python3基础教程之递归函数简单示例
Jun 07 Python
Python中的self用法详解
Aug 06 Python
Python使用python-docx读写word文档
Aug 26 Python
Django 实现外键去除自动添加的后缀‘_id’
Nov 15 Python
python ctypes库2_指定参数类型和返回类型详解
Nov 19 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
如何在PHP中使用Oracle数据库(6)
2006/10/09 PHP
php简单对象与数组的转换函数代码(php多层数组和对象的转换)
2011/05/18 PHP
Drupal7连接多个数据库及常见问题解决
2014/03/02 PHP
PHP对象克隆clone用法示例
2016/09/28 PHP
javascript 三种编解码方式
2010/02/01 Javascript
jquery.AutoComplete.js中文修正版(支持firefox)
2010/04/09 Javascript
javascript算法题 求任意一个1-9位不重复的N位数在该组合中的大小排列序号
2012/07/21 Javascript
基于jquery实现后台左侧菜单点击上下滑动显示
2013/04/11 Javascript
深入理解JavaScript 闭包究竟是什么
2013/04/12 Javascript
jQuery选择id属性带有点符号元素的方法
2015/03/17 Javascript
Jquery网页内滑动缓冲导航的实现代码
2015/04/05 Javascript
js鼠标跟随运动效果
2017/03/11 Javascript
BootStrap 导航条实例代码
2017/05/18 Javascript
基于vue cli重构多页面脚手架过程详解
2018/01/23 Javascript
Vue+webpack项目基础配置教程
2018/02/12 Javascript
element-ui 实现响应式导航栏的示例代码
2020/05/08 Javascript
基于javascript canvas实现五子棋游戏
2020/07/08 Javascript
vue实现点击出现操作弹出框的示例
2020/11/05 Javascript
[36:41]完美世界DOTA2联赛循环赛FTD vs Magma第一场 10月30日
2020/10/31 DOTA
python自带的http模块详解
2016/11/06 Python
python定时关机小脚本
2018/06/20 Python
pandas 对日期类型数据的处理方法详解
2019/08/08 Python
python实现两个一维列表合并成一个二维列表
2019/12/02 Python
python图形开发GUI库wxpython使用方法详解
2020/02/14 Python
python将dict中的unicode打印成中文实例
2020/05/11 Python
python3.8.1+selenium实现登录滑块验证功能
2020/05/22 Python
python连接手机自动搜集蚂蚁森林能量的实现代码
2021/02/24 Python
详解HTML5中表单验证的8种方法介绍
2016/12/19 HTML / CSS
DC Shoes澳大利亚官方网上商店:购买DC鞋子
2019/10/25 全球购物
外贸业务员岗位职责
2013/11/24 职场文书
广告设计应届生求职信
2014/03/01 职场文书
医学生临床实习自我评价
2014/03/07 职场文书
关于读书的演讲稿500字
2014/08/27 职场文书
市场营销计划书
2015/01/17 职场文书
闪闪的红星观后感
2015/06/08 职场文书
Python 线程池模块之多线程操作代码
2021/05/20 Python