人脸识别代码执行遇TypeError:imgModeList[3]赋值报错求助
人脸识别项目报错排查:TypeError: int()参数不能为NoneType
问题描述
开发人脸识别项目时,执行到imgBackground[44:44 + 633, 808:808 + 414] = imgModeList[3]代码行时抛出错误,错误信息:
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
已确认切片逻辑正确,注释该行后仍存在问题,附上代码片段及报错栈。
代码片段
while True: success, img = cap.read() img_small = cv2.resize(img, (0, 0), None, 0.25, 0.25) img_small = cv2.cvtColor(img_small, cv2.COLOR_BGR2RGB) faceCurFrame = face_recognition.face_locations(img_small) encodeCurFrame = face_recognition.face_encodings(img_small, faceCurFrame) for encodeFace, faceLoc in zip(encodeCurFrame, faceCurFrame): matches = face_recognition.compare_faces(encodeListKnown, encodeFace) faceDist = face_recognition.face_distance(encodeListKnown, encodeFace) print("matches", matches) print("faceDis", faceDist) matchIndex = np.argmin(faceDist) print("Match Index", matchIndex) if matches[matchIndex]: print("Known face was detected") print(studentsId[matchIndex]) imgBackground[162:162 + 480, 55:55 + 640] = img imgBackground[44:44 + 633, 808:808 + 414] = imgModeList[3] # cv2.imshow("Webcam", img) cv2.imshow("Face Attendance", imgBackground) cv2.waitKey(1)
报错栈
Traceback (most recent call last): File "C:\Users\Tony Alosius\PycharmProjects\pythonProject1\main.py", line 52, in <module> imgBackground[44:44 + 633, 808:808 + 414] = imgModeList[3] TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType' [ WARN:0] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
原因分析与解决方案
核心原因
imgModeList[3]为None:大概率是图像加载失败(比如路径错误、文件损坏),导致列表对应位置未获取到有效图像数组。- 摄像头读取失败:
cap.read()返回success=False时,img为None,后续赋值给imgBackground切片也会触发同类错误,这也是注释目标行后仍报错的原因。 imgBackground未正确初始化:如果imgBackground本身是None,任何切片赋值操作都会失败。
具体修复步骤
校验
imgModeList的图像加载
确保每个图像都成功加载,避免列表中出现None:imgModeList = [] # 假设modePaths是图像路径列表 for path in modePaths: img = cv2.imread(path) if img is not None: imgModeList.append(img) else: print(f"加载失败:{path}") # 检查索引3是否有效 if len(imgModeList) <= 3 or imgModeList[3] is None: print("错误:imgModeList[3]未有效加载") # 可选择退出或使用默认图像增加摄像头读取有效性判断
在使用img前先确认摄像头读取成功:while True: success, img = cap.read() if not success: print("摄像头读取失败,退出循环") break # 后续图像处理代码...确认
imgBackground初始化正确
确保imgBackground是预先创建的有效numpy数组,比如:# 示例:创建一个指定尺寸的黑色背景图 imgBackground = np.zeros((720, 1280, 3), dtype=np.uint8) # 或读取背景图像 imgBackground = cv2.imread("background_path.jpg") if imgBackground is None: print("背景图加载失败") exit()
内容的提问来源于stack exchange,提问作者Tony Alosius
相关产品推荐
相关产品推荐

