Python代码抛出IndexError: list index out of range问题求助
问题解决:IndexError: list index out of range
核心问题分析
你的代码有两个关键问题触发索引越界错误:
- 人脸编码列表混入空值:
face_recognition.face_encodings(img)返回的是人脸编码的列表(一张图可能无人脸或多张人脸),你直接把这个列表塞进encodeList,如果某张图没检测到人脸,就会存入空列表。后续和摄像头捕获的人脸编码对比时,空值会打乱索引对应关系,触发越界。 - 编码列表与标签列表长度不匹配:即使某张图片没检测到人脸,你还是把它的文件名加入了
classNames,但encodeListKnown里对应的位置是空的,后续通过matchIndex取classNames[matchIndex]时就会对应错误,甚至越界。
修复后的代码
import cv2 import numpy as np import face_recognition import os import pickle path = 'known_faces' images = [] classNames = [] myList = os.listdir(path) print(myList) for cl in myList: curImg = cv2.imread(f'{path}/{cl}') # 过滤读取失败的无效图片 if curImg is not None: images.append(curImg) classNames.append(os.path.splitext(cl)[0]) print(classNames) def findEncodings(images): encodeList = [] for img in images: img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) encodes = face_recognition.face_encodings(img) # 只保留检测到人脸的编码(取第一张脸的编码) if encodes: encodeList.append(encodes[0]) return encodeList encodeListKnown = findEncodings(images) # 强制检查编码与标签数量一致,提前排查问题 assert len(encodeListKnown) == len(classNames), "编码数量与标签数量不匹配,请检查known_faces文件夹中的图片是否都包含清晰人脸" print('encode complete') cap = cv2.VideoCapture(0) while True: success, img = cap.read() if not success: print("无法读取摄像头画面") break imgS = cv2.resize(img,(0,0),None,0.25,0.25) imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB) facesCurFrame = face_recognition.face_locations(imgS) encodeCurFrame = face_recognition.face_encodings(imgS,facesCurFrame) for encodeFace,faceLoc in zip(encodeCurFrame, facesCurFrame): matches = face_recognition.compare_faces(encodeListKnown,encodeFace) faceDis = face_recognition.face_distance(encodeListKnown,encodeFace) print(faceDis) matchIndex = np.argmin(faceDis) if matches[matchIndex]: name = classNames[matchIndex].upper() print(name) # 按q键退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
关键修复点
- 读取图片时增加非空判断,过滤无效图片
- 人脸编码时只保留检测到人脸的结果,确保
encodeListKnown和classNames长度严格一致 - 增加断言检查编码与标签数量匹配,提前发现问题
- 补充摄像头读取失败的处理逻辑,以及循环退出机制
内容的提问来源于stack exchange,提问作者The Lord
相关产品推荐
相关产品推荐

