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

基于OpenCV Haar Cascade的实时人脸识别系统索引越界问题排查

家庭安防人脸识别系统索引越界问题解决

问题描述

搭建基于Haar Cascade的家庭安防实时人脸识别系统,期望识别names数组中记录的人员或标记为"unknown",但运行代码时触发索引越界错误。

运行代码

# iniciate id counter
userID = 0

# names related to Userids:
names = ['Mike', 'Yakub', 'Brother C', 'Brother A', 'Robert', 'William']

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
cam.set(3, 640)  # set video widht
cam.set(4, 480)  # set video height

# Define min window size to be recognized bv face
minW = 0.1 * cam.get(3)
minH = 0.1 * cam.get(4)

while True:
    ret,img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.2,
        minNeighbors=5,
        minSize=(int(minW), int(minH)),
    )

    for (x, y, w, h) in faces:

        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

        userID, confidence = recognizer.predict(gray[y:y + h, x:x + w])

        # Check if confidence is less them 80 ==> "0" is perfect match
        if confidence < 80:
            userID = names[userID]
            confidence = "  {0}%".format(round(80 - confidence))
        else:
            userID = "unknown"
            confidence = "  {0}%".format(round(80 - confidence))

        cv2.putText(img, str(userID), (x + 5, y - 5), font, 1, (255, 255, 255), 2)
        cv2.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (255, 255, 0), 1)

    cv2.imshow('camera', img)

    k = cv2.waitKey(10) & 0xff  # Press 'ESC' for exiting video
    if k == 27:
        break

错误信息

userID = names[userID]
IndexError: list index out of range

Process finished with exit code 1

解决方案

错误根源

recognizer.predict()返回的userID超出了names列表的索引范围。names列表有6个元素,合法索引是0-5,但预测返回的ID可能大于等于6或为负数,导致访问列表时触发越界。

修复措施

  1. 增加ID合法性校验
    在访问names列表前,先判断userID是否在合法索引区间内,修改判断逻辑:
if confidence < 80 and 0 <= userID < len(names):
    userID = names[userID]
    confidence = "  {0}%".format(round(80 - confidence))
else:
    userID = "unknown"
    confidence = "  {0}%".format(round(80 - confidence))
  1. 校准训练数据与ID映射
    确认训练人脸识别模型时,分配的人员ID与names列表的索引完全对应。例如Mike对应ID0、Yakub对应ID1,以此类推,不能出现训练ID大于5的情况。

  2. 补全未定义变量
    代码中faceCascade、recognizer、font三个变量未初始化,需补充以下代码(替换模型路径为你的实际路径):

import cv2

# 初始化Haar级联分类器
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# 初始化人脸识别器并加载训练模型
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')  # 替换为你的训练模型路径
# 设置字体
font = cv2.FONT_HERSHEY_SIMPLEX

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:00:57