Python手部追踪音量控制脚本触发KeyError:2报错排查
报错根因
KeyError: 2触发的核心原因是HandTrackingModule的findPosition方法返回的bbox结构和你代码预期的不匹配:你的代码默认bbox是按索引存储[xmin, ymin, xmax, ymax]的列表,但实际运行时返回的bbox要么是键名非数字的字典,要么是长度不足的列表/空值,取索引2时直接触发错误。
注释掉面积计算代码后脚本不崩溃,只是因为跳过了访问bbox[2]的逻辑,后续依赖手部位置的音量控制逻辑自然也无法正常触发。
修复方案
最稳妥的修复方式是不依赖模块返回的bbox,直接从已经拿到的手部关键点列表lmList自行计算边界框,完全规避不同版本HandTrackingModule返回结构不一致的问题,修改步骤如下:
- 找到主循环里判断
len(lmList) != 0的代码块 - 把原来直接用模块返回bbox计算面积的逻辑,替换为自行计算bbox的代码,修改后的对应代码段如下:
while True: success, img = cap.read() img = detector.findHands(img) lmList, bbox = detector.findPosition(img, draw=True) if len(lmList) != 0: # 从21个手部关键点自行计算边界框,兼容所有版本的HandTrackingModule x_coords = [point[1] for point in lmList] y_coords = [point[2] for point in lmList] xmin, xmax = min(x_coords), max(x_coords) ymin, ymax = min(y_coords), max(y_coords) # 组装为代码预期的[xmin, ymin, xmax, ymax]格式 bbox = [xmin, ymin, xmax, ymax] # 原有面积计算逻辑无需改动 area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1]) // 100 if 250 < area < 1000: # 后续距离计算、音量映射、手指判断逻辑全部保留即可 length, img, lineInfo = detector.findDistance(4, 8, img) volBar = np.interp(length, [50, 200], [400, 150]) volPer = np.interp(length, [50, 200], [0, 100]) smoothness = 10 volPer = smoothness * round(volPer / smoothness) fingers = detector.fingersUp() if not fingers[4]: volume.SetMasterVolumeLevelScalar(volPer / 100, None) cv2.circle(img, (lineInfo[4], lineInfo[5]), 15, (0, 225, 0), cv2.FILLED) colorVol = (225, 0 ,0) else: colorVol = (0, 255, 0) # 后续绘制、FPS计算逻辑无需改动 cv2.rectangle(img, (50, 150), (85, 400), (225, 0, 0), 3) cv2.rectangle(img, (50, int(volBar)), (85, 400), (225, 0, 0), cv2.FILLED) cv2.putText(img, f' {int(volPer)} %', (40, 450), cv2.FONT_HERSHEY_COMPLEX, 1, (225, 0, 0), 3) cVol = int(volume.GetMasterVolumeLevelScalar() * 100) cv2.putText(img, f'Vol Set: {int(cVol)}', (400, 50), cv2.FONT_HERSHEY_COMPLEX, 1, colorVol, 3) cTime = time.time() fps = 1/(cTime - pTime) pTime = cTime cv2.putText(img, f'FPS: {int(fps)}', (40, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 3) cv2.imshow("image", img) cv2.waitKey(1)
验证说明
- 上述修改默认
lmList的每个元素格式为[关键点序号, x坐标, y坐标],这是公开版HandTrackingModule的标准返回格式,无兼容问题 - 修改后手部进入画面时不会再触发KeyError,距离判断、音量调节逻辑可正常运行
- 如果需要确认原模块返回的bbox结构,可在
lmList, bbox = detector.findPosition(img, draw=True)下加一行print(bbox),控制台输出的内容即为原模块实际返回的bbox值,可对照调整取值逻辑
内容的提问来源于stack exchange,提问作者Stevon
相关产品推荐
相关产品推荐

