OpenCV杂谈_10


一. 需要做的前期准备

  1. 环境配置:
    Python版本:3.6.0(这里需要注意一下,如果你的python版本为>=3.9,对于dlib包的导入将会很困难,具体导入方法博主还没有解决)
    功能包:scipy (1.5.4)、imutils (0.5.4)、argparse (1.4.0)、dlib (19.22.0)、opencv-python (4.5.2.54)
  2. 如果想要对录制好的视频进行处理则需要提前获得的视频
  3. 下载shape_predictor_68_face_landmarks.dat,作者把它传到了云盘里,需要的自取:链接在此 提取码:demo
  4. 一个用的顺手的IDE(本人推荐Pycharm)

二. 须知

  1. 68 points face landmark:
  2. 眼睛距离计算

三. 源码如下(闭眼检测)

import cv2
import dlib
from scipy.spatial import distancedef calculate_EAR(eye):
"""计算眼睛之间的距离"""A = distance.euclidean(eye[1], eye[5])B = distance.euclidean(eye[2], eye[4])C = distance.euclidean(eye[0], eye[3])ear_aspect_ratio = (A + B) / (2.0 * C)return ear_aspect_ratio# 读取webcamera、dector、dat文件
cap = cv2.VideoCapture(0)
hog_face_detector = dlib.get_frontal_face_detector()
dlib_facelandmark = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")# 循环处理
while True:_, frame = cap.read()gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # 转灰度faces = hog_face_detector(gray)  # 检测脸部特征点for face in faces:face_landmarks = dlib_facelandmark(gray, face)leftEye = []rightEye = []# 找左眼 for n in range(36, 42):  # 36~41 代表左眼x = face_landmarks.part(n).xy = face_landmarks.part(n).yleftEye.append((x, y))next_point = n + 1if n == 41:  # 绕回来好实现最后对眼睛的画圈next_point = 36x2 = face_landmarks.part(next_point).xy2 = face_landmarks.part(next_point).ycv2.line(frame, (x, y), (x2, y2), (0, 255, 0), 1)  # 圈出左眼# 找右眼for n in range(42, 48):  # 42~47代表右眼x = face_landmarks.part(n).xy = face_landmarks.part(n).yrightEye.append((x, y))next_point = n + 1if n == 47:  # 绕回来好实现对眼睛的画圈next_point = 42x2 = face_landmarks.part(next_point).xy2 = face_landmarks.part(next_point).ycv2.line(frame, (x, y), (x2, y2), (0, 255, 0), 1)  # 圈出右眼# 计算每只眼睛的睁开程度left_ear = calculate_EAR(leftEye)right_ear = calculate_EAR(rightEye)# 做个平均EAR = (left_ear + right_ear) / 2EAR = round(EAR, 2)if EAR < 0.26:  # 如果距离小于0.26,进行提示cv2.putText(frame, "WAKE UP", (20, 100),cv2.FONT_HERSHEY_SIMPLEX, 3, (0, 0, 255), 4)cv2.putText(frame, "Are you Sleepy?", (20, 400),cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 4)print("!!!")print(EAR)cv2.imshow("Are you Sleepy", frame)key = cv2.waitKey(1)if key == 27:break
cap.release()
cv2.destroyAllWindows()

四. 源码如下(眨眼次数计算,注释懒得写成中文了,自行理解)

from scipy.spatial import distance as dist
from imutils.video import FileVideoStream
from imutils.video import VideoStream
from imutils import face_utils
import imutils
import time
import dlib
import cv2def eye_aspect_ratio(eye):# compute the euclidean distances between the two sets of vertical eye landmarks (x, y)-coordinatesA = dist.euclidean(eye[1], eye[5])B = dist.euclidean(eye[2], eye[4])# compute the euclidean distance between the horizontal eye landmark (x, y)-coordinatesC = dist.euclidean(eye[0], eye[3])# compute the eye aspect ratioear = (A + B) / (2.0 * C)# return the eye aspect ratioreturn ear# read the dat file and video to be processed
p = 'shape_predictor_68_face_landmarks.dat'
v = "video.mp4"# define two constants, one for the eye aspect ratio to indicate
# blink and then a second constant for the number of consecutive frames the eye must be below the thresholdEYE_AR_THRESH = 0.25
EYE_AR_CONSEC_FRAMES = 2# initialize the frame counters and the total number of blinks
COUNTER = 0
TOTAL = 0# initialize dlib's face detector (HOG-based) and then create the facial landmark predictorprint("[INFO] loading facial landmark predictor...")
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(p)# grab the indexes of the facial landmarks for the left and right eye, respectively
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]# start the video stream thread
print("[INFO] starting video stream thread...")# when you want use your wbcamera un# these two lines
# vs = FileVideoStream(v).start()
# fileStream = True# when you want to read videos use these two lines
vs = VideoStream(src=0).start()
fileStream = Falsetime.sleep(1.0)# loop over frames from the video stream
while True:# if this is a file video stream, then we need to check if there any more frames left in the buffer to processif fileStream and not vs.more():break# grab the frame from the threaded video file stream, resize it, and convert it# to grayscale channels)frame = vs.read()frame = imutils.resize(frame, width=450)gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)rects = detector(gray, 0)# loop over the face detectionsfor rect in rects:# determine the facial landmarks for the face region, then convert# the facial landmark (x, y)-coordinates to a NumPy arrayshape = predictor(gray, rect)shape = face_utils.shape_to_np(shape)# extract the left and right eye coordinates, then use the coordinates to compute the eye aspect ratio for both eyesleftEye = shape[lStart:lEnd]rightEye = shape[rStart:rEnd]leftEAR = eye_aspect_ratio(leftEye)rightEAR = eye_aspect_ratio(rightEye)# average the eye aspect ratio together for both eyesear = (leftEAR + rightEAR) / 2.0# compute the convex hull for the left and right eye, then visualize each of the eyesleftEyeHull = cv2.convexHull(leftEye)rightEyeHull = cv2.convexHull(rightEye)cv2.drawContours(frame, [leftEyeHull], -1, (0, 255, 0), 1)cv2.drawContours(frame, [rightEyeHull], -1, (0, 255, 0), 1)# check to see if the eye aspect ratio is below the blink threshold, and if so, increment the blink frame counterif ear < EYE_AR_THRESH:COUNTER += 1# otherwise, the eye aspect ratio is not below the blink thresholdelse:# if the eyes were closed for a sufficient number of then increment the total number of blinksif COUNTER >= EYE_AR_CONSEC_FRAMES:TOTAL += 1# reset the eye frame counterCOUNTER = 0# draw the total number of blinks on the frame along with the computed eye aspect ratio for the framecv2.putText(frame, "Blinks: {}".format(TOTAL), (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)cv2.putText(frame, "EAR: {:.2f}".format(ear), (300, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)cv2.putText(frame, "COUNTER: {}".format(COUNTER), (140, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)# show the frame show the framecv2.imshow("Frame", frame)key = cv2.waitKey(1) & 0xFF# if the `q` key was pressed, break from the loopif key == ord("q"):break# cleanup
cv2.destroyAllWindows()
vs.stop()

五. 感悟与分享

  1. 有关闭眼检测的教程:https://www.youtube.com/watch?v=OCJSJ-anywc&t=305s&ab_channel=MisbahMohammed
  2. 有关眨眼次数计算的教程:https://www.pyimagesearch.com/2017/04/24/eye-blink-detection-opencv-python-dlib/
    以上内容均为英文,且需要翻墙。
  3. 其实原理并不复杂,就是通过检测出眼睛,之后再计算眼皮之间的距离,来获得最终想要的数据。

如有问题,敬请指正。欢迎转载,但请注明出处。

如何使用OpenCV-Python-dlib实现有关闭眼的检测、眨眼次数的计算?(附源码,绝对可用)相关推荐

  1. python:pyqt5+mysql=学生信息管理系统(图文并茂,超详细, 附源码)——增删改查篇

    python:pyqt5+mysql=学生信息管理系统(图文并茂,超详细, 附源码)--增删改查篇 前言 一.主界面的样式 二.学生信息的增,删,改,查 1.增加学生信息 2.删除学生信息 3.更改学 ...

  2. opencv判断 线夹角_python opencv实现直线检测并测出倾斜角度(附源码+注释)

    由于学习需要,我想要检测出图片中的直线,并且得到这些直线的角度.于是我在网上搜了好多直线检测的代码,但是没有搜到附有计算直线倾斜角度的代码,所以我花了一点时间,自己写了一份直线检测并测出倾斜角度的代码 ...

  3. python抢购火车票源代码_Python动刷新抢12306火车票的代码(附源码)

    摘要:这篇Python开发技术栏目下的"Python动刷新抢12306火车票的代码(附源码)",介绍的技术点是"12306火车票.Python.12306.附源码.火车票 ...

  4. python全景图像拼接_超详讲解图像拼接/全景图原理和应用 | 附源码

    研究好玩又有用的技术第 008 期 在学习中发现快乐,在应用找到价值.这是我第八期分享图像技术应用的文章. 前七期欢迎阅读和分享: 概述 作者:Thalles Silva 编译:AI算法与图像处理 图 ...

  5. 【python】利用python的tkinter-canvas函数绘制哆啦A梦过程详解(附源码)

    1 引 言 绘制哆啦A梦的过程,其实是对哆啦A梦进行拆解的过程,得先构思出他的头部.眼睛.鼻子.嘴巴.胡须.身体.铃铛.口袋.手以及脚等(如下图所示),才能进行下一步的绘画工作.心中有丘壑,方能水到渠 ...

  6. 【Python工具】Python实现一款支持各大平台的视频下载器 | 附源码

    相关文件 想学Python的小伙伴可以关注小编的公众号[Python日志] 有很多的资源可以白嫖的哈,不定时会更新一下Python的小知识的哈!! 需要源码的小伙伴可以在公众号回复视频下载器 简介 一 ...

  7. Python实战案例,PyQt5模块,实现疫情信息快速查看工具(附源码)

    前言 今天给大家介绍的是Python疫情信息快速查看工具,在这里给需要的小伙伴们代码,并且给出一点小心得. PyQt概述 PyQt5是Qt框架的Python语言实现,由Riverbank Comput ...

  8. 免费直播!用Python开发人脸识别程序,零基础也能学(附源码)

    在当今社会人脸识别技术应用的范围越来越广泛,全球很多商业活动都已经从中获益:人脸自动对焦和笑脸快门技术,人脸识别门禁,人脸识别支付等许多方面. 人脸识别技术的使用在接下来的几年内还会继续增长,还没掌握 ...

  9. 今天不抠图,Python实现一键换底片!想换什么换什么(附源码)

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 生活中我们会拍很多的证件照,有的要求红底,有的是白底,有的是蓝底,今天不通 ...

  10. Python突破12306最后一道防线,实现自动抢票(附源码)

    一年一度的春运又来了,今年我自己写了个抢票脚本.使用Python+Splinter自动刷新抢票,可以成功抢到.(依赖自己的网络环境太厉害,还有机器的好坏) Splinter是一个使用Python开发的 ...

最新文章

  1. Table of Contents - Tomcat
  2. 生死6小时!!!!!!!!!!!!!!!!1
  3. No changes detected解决方案
  4. mysql adminer 导入csv_mysql导入csv的4种报错的解决方法
  5. RSA公私钥加解密方式-工具类
  6. oracle数据库抽取到gp,Oracle迁移数据到Greenplum
  7. U66785 行列式求值
  8. 1-算法 排序 选择排序
  9. java weblogic admin,weblogic admin 不能重起服务(Server may already be running)
  10. ArcObjects操作PageLayoutControl中元素位置,以图框、ITextSymbol为例
  11. (转)AIX rootvg 镜像创建与磁盘更换
  12. java动手动脑之多态
  13. 关于图像分割Snake算法(c#)的一些不解之惑,望大神指点的拙见
  14. 在 OpenBSD 系统下的安装PHP
  15. HTML ASP VBSCRIPT JAVASCRIPT SKILLS 常见问题
  16. 微众银行助力普惠金融实现高质量发展
  17. C#使用BouncyCastle来实现私钥加密,公钥解密的方法
  18. 迅捷路由连接服务器未响应,fast迅捷路由器设置:连上无线信号上不了网,怎么办?...
  19. Vultr 怎么修改 Root 账户密码
  20. 史上最全RabbitMq详解

热门文章

  1. 计算机专业期刊参考文献,优秀计算机期刊文章参考文献 优秀计算机专著类参考文献有哪些-免费论文范文...
  2. 基于Proteus学习单片机系列(十一)——LCD12864
  3. 别让西药毁了凉茶!盒马牵手平安堂,能放心喝的凉茶来了
  4. 计算机组成原理课程设计基于cop2000
  5. Lotka–Volterra equation Competitive Lotka–Volterra equations
  6. 基于BP神经网络控制+Simulink双闭环直流调速系统仿真
  7. 最优传输论文(十四):Generative Adversarial Nets论文原理
  8. 基于Java Web的航空售票管理系统(酒店管理系统,图书管理系统、学生管理系统)
  9. Xftp7免费版(个人)下载链接
  10. 基于SSM小区物业管理系统