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操作mysql数据库
Mar 05 Python
Python实现输出程序执行进度百分比的方法
Sep 16 Python
Python入门之三角函数atan2()函数详解
Nov 08 Python
python调用c++传递数组的实例
Feb 13 Python
详解Python爬取并下载《电影天堂》3千多部电影
Apr 26 Python
Python button选取本地图片并显示的实例
Jun 13 Python
Django Rest framework权限的详细用法
Jul 25 Python
PyTorch在Windows环境搭建的方法步骤
May 12 Python
Python pip安装模块提示错误解决方案
May 22 Python
Python字典fromkeys()方法使用代码实例
Jul 20 Python
Python实现Appium端口检测与释放的实现
Dec 31 Python
如何用Python编写一个电子考勤系统
Feb 08 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
第九节 绑定 [9]
2006/10/09 PHP
php fckeditor 调用的函数
2009/06/21 PHP
php一些错误处理的方法与技巧总结
2013/08/10 PHP
php mysql实现mysql_select_db选择数据库
2016/12/30 PHP
Draggable Elements 元素拖拽功能实现代码
2011/03/30 Javascript
js 页面关闭前的出现提示的实现代码
2011/05/25 Javascript
TextArea设置MaxLength属性最大输入值的js代码
2012/12/21 Javascript
jquery必须知道的一些常用特效方法及使用示例(整理)
2013/06/24 Javascript
window.showModalDialog()返回值的学习心得总结
2014/01/07 Javascript
js时间戳转为日期格式的方法
2015/12/28 Javascript
基于JS实现新闻列表无缝向上滚动实例代码
2016/01/22 Javascript
JavaScript通过代码调用Flash显示的方法
2016/02/02 Javascript
浅析jQuery中使用$所引发的问题
2016/05/29 Javascript
详解webpack自动生成html页面
2017/06/29 Javascript
node 使用 async 控制并发的方法
2018/05/07 Javascript
vue 点击展开显示更多(点击收起部分隐藏)
2019/04/09 Javascript
微信小程序实现多行文字超出部分省略号显示功能
2019/10/23 Javascript
微信小程序关键字变色实现代码实例
2019/12/13 Javascript
JS自定义滚动条效果
2020/03/13 Javascript
JavaScript实现五子棋小游戏
2020/10/26 Javascript
JS中箭头函数与this的写法和理解
2021/01/14 Javascript
Python复制目录结构脚本代码分享
2015/03/06 Python
详解Python爬虫的基本写法
2016/01/08 Python
Python 操作MySQL详解及实例
2017/04/30 Python
Python创建普通菜单示例【基于win32ui模块】
2018/05/09 Python
对Python3 pyc 文件的使用详解
2019/02/16 Python
python接口自动化(十六)--参数关联接口后传(详解)
2019/04/16 Python
python BlockingScheduler定时任务及其他方式的实现
2019/09/19 Python
pycharm工具连接mysql数据库失败问题
2020/04/01 Python
Tensorflow实现将标签变为one-hot形式
2020/05/22 Python
Calphalon美国官网:美国顶级锅具品牌
2020/02/05 全球购物
Diesel美国网上商店:意大利牛仔时装品牌
2020/12/10 全球购物
PHP面试题附答案
2015/11/28 面试题
写自荐信要注意什么
2013/12/26 职场文书
2015秋学期开学寄语
2015/05/28 职场文书
2019幼儿教师求职信(3篇)
2019/09/20 职场文书