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

Python+MediaPipe手部检测中fingersUp函数出现IndexError: list index out of range问题求助

解决MediaPipe手部检测中IndexError: list index out of range的问题

看起来你遇到的问题是在调用fingersUp函数时,因为self.lmList为空或者没有正确填充,导致索引越界。我来帮你一步步排查和解决:

错误原因分析

你的错误出在这一行:

if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:

IndexError说明self.lmList是空列表,或者你尝试访问的索引超出了它的实际长度。主要有几个可能:

  • 你在调用fingersUp之前,没有调用findPosition函数,或者findPosition没有检测到任何手部关键点(比如画面里没有手),导致self.lmList是空的。
  • 你的代码里存在HTML实体转义问题:&gt;和&lt;应该替换成实际的>和<,否则会触发语法错误(不过你说的是索引错误,可能是复制时的格式问题)。
  • 另外,你的main函数入口有拼写错误:__main_&quot;应该是__main__,否则程序不会执行main函数。

具体解决方案

1. 在fingersUp中添加空值检查

在fingersUp函数开头先判断self.lmList是否为空,避免直接访问索引:

def fingersUp(self):
    # 先检查是否有手部关键点数据
    if not self.lmList:
        return []  # 或者返回[0,0,0,0,0]表示没有手指竖起
    fingers = []
    # Thumb
    if self.lmList[self.tipIds[0]][1] > self.lmList[self.tipIds[0] - 1][1]:
        fingers.append(1)
    else:
        fingers.append(0)
    # Fingers
    for id in range(1, 5):
        if self.lmList[self.tipIds[id]][2] < self.lmList[self.tipIds[id] - 2][2]:
            fingers.append(1)
        else:
            fingers.append(0)
    return fingers

2. 确保调用fingersUp的时机正确

只有在findPosition成功获取到关键点(也就是len(lmList) != 0)的时候,再调用fingersUp。比如修改你的main函数:

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList, bbox = detector.findPosition(img)
        if len(lmList) != 0:
            # 只有检测到手部关键点时才调用fingersUp
            fingers = detector.fingersUp()
            print(fingers)  # 可以打印测试结果
            
            cTime = time.time()
            fps = 1 / (cTime - pTime)
            pTime = cTime
            cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3)
        cv2.imshow("Image", img)
        cv2.waitKey(1)

3. 修复代码中的格式错误

  • 把代码里的&gt;替换为>,&lt;替换为<,否则Python会识别为无效语法。
  • 修复main函数的入口拼写错误:
if __name__ == "__main__":
    main()

4. 额外优化:处理多手情况

如果你的场景中可能出现多只手,findPosition的handNo参数需要根据实际检测到的手的数量来调整,避免访问不存在的手索引。比如可以遍历所有检测到的手:

def main():
    # ...其他代码
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        # 检查检测到的手的数量
        if detector.results.multi_hand_landmarks:
            for hand_idx in range(len(detector.results.multi_hand_landmarks)):
                lmList, bbox = detector.findPosition(img, handNo=hand_idx)
                if len(lmList) != 0:
                    fingers = detector.fingersUp()
                    print(f"手{hand_idx+1}的手指状态:", fingers)
        # ...FPS显示和窗口代码

这样调整后,应该就能避免索引越界的问题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:17:42