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

人脸识别程序人脸消失时崩溃:TypeError解包NoneType对象错误

人脸追踪程序崩溃问题解决(TypeError: cannot unpack non-iterable NoneType object)

问题分析

你的代码在未检测到人脸时崩溃,核心原因是findFace函数的return语句写在了for循环内部:当画面中没有人脸时,faces为空,for循环完全不执行,函数没有任何返回语句,默认返回None。而主循环里img, info = findFace(img)试图将None解包成两个变量,直接触发TypeError。

修复方案

把return语句移到for循环外部,确保无论是否检测到人脸,函数都能返回固定格式的(img, 数据)结构:

修改后的完整代码

def findFace(img):
    faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(imgGray, 1.2, 8)

    myFaceListC = []
    myFaceListArea = []

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
        cx = x + w // 2
        cy = y + h // 2
        area = w * h
        cv2.circle(img, (cx,cy),5,(204,51,128),cv2.FILLED)
        myFaceListC.append([cx, cy])
        myFaceListArea.append(area)
    
    # 将return移到循环外,确保始终返回有效结构
    if len(myFaceListArea) != 0:
        i = myFaceListArea.index(max(myFaceListArea))
        return img, [myFaceListC[i], myFaceListArea[i]]
    else:
        return img, [[0, 0], 0]

Cap = cv2.VideoCapture(0)
while True:
    _, img = Cap.read()
    img, info = findFace(img)
    print("Area", info[1], "Center", info[0])
    cv2.imshow("Output", img)
    cv2.waitKey(1)

关键修改点

  • 移除了主循环中多余的findFace(img)调用(重复调用会导致画面重复处理,无意义)
  • 将原本在for循环内的return逻辑移到循环结束后,保证即使没有人脸,函数也会返回img, [[0,0], 0]的有效结构,避免返回None

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:40:47