这篇教程Python人脸检测实战之疲劳检测写得很实用,希望能帮到您。 今天我们实现疲劳检测。 如果眼睛已经闭上了一段时间,我们会认为他们开始打瞌睡并发出警报来唤醒他们并引起他们的注意。我们测试一段视频来展示效果。同时代码中保留开启摄像头的的代码,取消注释即可使用。 
使用 OpenCV 构建犯困检测器要开始我们的实现,打开一个新文件,将其命名为 detect_drowsiness.py ,并插入以下代码: # import the necessary packagesfrom scipy.spatial import distance as distfrom imutils.video import VideoStreamfrom imutils import face_utilsfrom threading import Threadimport numpy as npimport playsoundimport argparseimport imutilsimport timeimport dlibimport cv2 导入们所需的 Python 包。 我们还需要 imutils 包,我的一系列计算机视觉和图像处理功能,以便更轻松地使用 OpenCV。 如果您的系统上还没有安装 imutils,您可以通过以下方式安装/升级 imutils: pip install --upgrade imutils 还将导入 Thread 类,以便我们可以在与主线程不同的线程中播放我们的警报,以确保我们的脚本不会在警报响起时暂停执行。 为了真正播放我们的 WAV/MP3 闹钟,我们需要 playsound 库,这是一个纯 Python 的跨平台实现,用于播放简单的声音。 playsound 库可以通过 pip 方便地安装: 但是,如果您使用的是 macOS(就像我为这个项目所做的那样),您还需要安装 pyobjc,否则当您实际尝试播放声音时,您将收到与 AppKit 相关的错误: 接下来,我们需要定义 sound_alarm 函数,该函数播放音频文件: def sound_alarm(path): # play an alarm sound playsound.playsound(path) 定义 eye_aspect_ratio 函数,该函数用于计算垂直眼睛界标之间的距离与水平眼睛界标之间的距离之比: def eye_aspect_ratio(eye): # compute the euclidean distances between the two sets of # vertical eye landmarks (x, y)-coordinates A = dist.euclidean(eye[1], eye[5]) B = dist.euclidean(eye[2], eye[4]) # compute the euclidean distance between the horizontal # eye landmark (x, y)-coordinates C = dist.euclidean(eye[0], eye[3]) # compute the eye aspect ratio ear = (A + B) / (2.0 * C) # return the eye aspect ratio return ear 由于OpenCV不能直接绘制中文,我们还需定义绘制中文的方法: def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20): if (isinstance(img, np.ndarray)): # 判断是否OpenCV图片类型 img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # 创建一个可以在给定图像上绘图的对象 draw = ImageDraw.Draw(img) # 字体的格式 fontStyle = ImageFont.truetype( "font/simsun.ttc", textSize, encoding="utf-8") # 绘制文本 draw.text((left, top), text, textColor, font=fontStyle,stroke_width=2) # 转换回OpenCV格式 return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR) 接下来,定义命令行参数: # construct the argument parse and parse the argumentsap = argparse.ArgumentParser()ap.add_argument("-p", "--shape-predictor", required=True, help="path to facial landmark predictor")ap.add_argument("-v", "--video", type=str, default="", help="path to input video file")ap.add_argument("-a", "--alarm", type=str, default="", help="path alarm .WAV file")ap.add_argument("-w", "--webcam", type=int, default=0, help="index of webcam on system")args = vars(ap.parse_args()) 犯困检测器需要一个命令行参数,后跟两个可选参数,每个参数的详细信息如下: Win10安装dlib GPU过程详解 利用python爬取城市公交站点
|