疲劳检测(嘴部)

import cv2
import dlib
import numpy as np
from imutils import face_utils


def mouth_aspect_ratio(mouth):
    A = np.linalg.norm(mouth[2] - mouth[9])  # 51, 59
    B = np.linalg.norm(mouth[4] - mouth[7])  # 53, 57
    C = np.linalg.norm(mouth[0] - mouth[6])  # 49, 55
    mar = (A + B) / (2.0 * C)
    return mar



mar1=0.6
mar2=3
mcounter=0
mtotal=0

print("loading,请稍后~")
# 打开摄像头
cap = cv2.VideoCapture(0)
# 加载人脸检测模块,获得脸部位置检测器
detector = dlib.get_frontal_face_detector()
# 第二步:使用dlib.shape_predictor获得脸部特征位置检测器
predictor = dlib.shape_predictor('F:/fatigue1/shape_predictor_68_face_landmarks.dat')
while True:
    # 读取图片并存在frame中。
    ret, frame = cap.read()
    # 把frame进行灰度处理
    gray = cv2.cvtColor(frame, code=cv2.COLOR_BGR2GRAY)
    # 识别人脸,第二个参数越大,代表讲原图放大多少倍在进行检测,提高小人脸的检测效果。
    faces = detector(gray, 1)
    # 画人脸识别的框
    for face in faces:
        x1 = face.left()
        y1 = face.top()
        x2 = face.right()
        y2 = face.bottom()
        # 对frame进行画框
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255))
        # 在gray中识别图片的face中提取特征点
        # 获取68个特征点的坐标

        #将脸部特征信息转换为数组array的格式
        shape = predictor(gray, face)
        for n in range(0, 68):
            x = shape.part(n).x
            y = shape.part(n).y
            cv2.circle(frame, (x, y), 1, (0, 0, 255))
        shape = face_utils.shape_to_np(shape)
        (mStart, mEnd) = face_utils.FACIAL_LANDMARKS_68_IDXS["mouth"]

        mouth = shape[mStart:mEnd]
        mar = mouth_aspect_ratio(mouth)
        if mar > mar1:  # 张嘴阈值0.5
            mcounter+= 1
            cv2.putText(frame, "Yawning!", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        else:
            # 如果连续3次都小于阈值,则表示打了一次哈欠
            if mcounter >= mar2:  # 阈值:3
                mtotal += 1
            # 重置嘴帧计数器
            mcounter = 0
        print("mar:{}".format(mar))
        cv2.putText(frame, "Yawning: {}".format(mtotal), (150, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        cv2.putText(frame, "mCOUNTER: {}".format(mcounter), (300, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        cv2.putText(frame, "MAR: {:.2f}".format(mar), (480, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

    cv2.imshow("img", frame)
    key = cv2.waitKey(500)
    if key == ord('q'):
        break
cap.release()
cv2.destroyAllWindows

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值