You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+OpenCV+dlib眨眼检测报错:NoneType与NoneType无法执行+运算

解决眨眼检测代码中的TypeError问题

你遇到的这个TypeError问题根源非常清晰——你的get_blinking_ratio函数没有返回计算好的ratio值,导致调用它得到的left_eye_ratio和right_eye_ratio都是None类型,自然没法执行加法运算。

直接给函数添加返回语句就能解决核心问题,同时我也帮你调整了代码里的几个小细节,避免其他潜在问题,下面是修正后的完整代码:

import cv2
import dlib
from math import hypot

cap = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
# 修正路径:用原始字符串避免反斜杠转义,同时移除多余空格
predictor = dlib.shape_predictor(r"C:\Users\Asirajdin\dev\shape_predictor_68_face_landmarks\shape_predictor_68_face_landmarks.dat")

def midpoint(p1, p2):
    return int((p1.x + p2.x)/2), int((p1.y + p2.y)/2)

font = cv2.FONT_HERSHEY_SIMPLEX

def get_blinking_ratio(eye_points, facial_landmarks):
    left_point = (facial_landmarks.part(eye_points[0]).x, facial_landmarks.part(eye_points[0]).y)
    right_point = (facial_landmarks.part(eye_points[3]).x, facial_landmarks.part(eye_points[3]).y)
    centre_top = midpoint(facial_landmarks.part(eye_points[1]), facial_landmarks.part(eye_points[2]))
    centre_bottom = midpoint(facial_landmarks.part(eye_points[5]), facial_landmarks.part(eye_points[4]))
    hor_line = cv2.line(frame, left_point, right_point, (0, 255,0), 2)
    ver_line = cv2.line(frame, centre_top, centre_bottom, (0, 255,0), 2)
    hor_line_length = hypot((left_point[0] - right_point[0]), (left_point[1] - right_point[1]))
    ver_line_length = hypot((centre_top[0] - centre_bottom[0]), (centre_top[1] - centre_bottom[1]))
    ratio = hor_line_length/ver_line_length
    # 关键修复:返回计算好的眨眼比例值
    return ratio

while(True):
    _, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = detector(gray)
    for face in faces:
        landmarks = predictor(gray, face)
        left_eye_ratio = get_blinking_ratio([36, 37, 38, 39, 40, 41], landmarks)
        right_eye_ratio = get_blinking_ratio([42, 43, 44, 45, 46, 47], landmarks)
        blinking_ratio = ((left_eye_ratio + right_eye_ratio) / 2)
        # 调整字体参数,避免文字过大超出画面
        if blinking_ratio > 5.7:
            cv2.putText(frame, "BLINKING", (50, 150), font, 2, (255, 0, 0), 3)
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()

额外细节说明:

  • 修复了模型路径问题:原路径包含多余空格,且Windows系统下的反斜杠需要用原始字符串(r"")包裹,避免转义错误;
  • 调整了cv2.putText的参数:把字体大小从5改为2,增加了线条厚度,避免"BLINKING"文字过大无法完整显示;
  • 核心修复点:给get_blinking_ratio函数添加return ratio语句,让函数能返回计算结果,这样后续的加法运算就能正常执行。

内容的提问来源于stack exchange,提问作者Sirajdin Adeshina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:07:46