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

Python开发AR虚拟鼠标调用cvzone fingersUp报UnboundLocalError求助

错误原因
  • 核心问题是你没有先判断是否检测到人手,就直接调用detector.fingersUp()方法。cvzone官方的HandDetector.fingersUp()方法内部逻辑中,当没有检测到手部关键点时,存储手指状态的fingers变量不会完成初始化就被返回,直接触发UnboundLocalError。
  • 你的代码还存在两个隐藏bug:一是取指尖坐标时使用lmList[8][:1],切片返回长度为1的列表,赋值给x1、y1两个变量会直接抛出值错误;二是没有把手部相关操作都放到检测到手的判断分支中,未检测到手时调用x1、y1变量也会触发未定义错误。
解决方案

把所有和手部操作相关的逻辑,全部放到len(lmList) != 0的判断分支内,同时修正指尖坐标取值的切片错误,修改后的核心代码如下:

while True:
    # 1. Find hand Landmarks
    success, img = cap.read()
    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img)

    # 只有检测到手才执行后续逻辑
    if len(lmList) != 0:
        # 2. Get the tip of the index and middle fingers,修正切片为[:2]取x、y两个值
        x1, y1 = lmList[8][:2]
        x2, y2 = lmList[12][:2]
    
        # 3. Check which fingers are up
        fingers = detector.fingersUp()
        print(fingers)
        cv2.rectangle(img, (frameR, frameR), (wCam - frameR, hCam - frameR),
        (255, 0, 255), 2)

        # 4. Only Index Finger : Moving Mode
        if fingers[1] == 1 and fingers[2] == 0:
            # 5. Convert Coordinates
            x3 = np.interp(x1, (frameR, wCam - frameR), (0, wScr))
            y3 = np.interp(y1, (frameR, hCam - frameR), (0, hScr))

            # 6. Smoothen Values
            clocX = plocX + (x3 - plocX) / smoothening
            clocY = plocY + (y3 - plocY) / smoothening
        
            # 7. Move Mouse
            autopy.mouse.move(wScr - clocX, clocY)
            cv2.circle(img, (x1, y1), 15, (255, 0, 255), cv2.FILLED)
            plocX, plocY = clocX, clocY
            
        # 8. Both Index and middle fingers are up : Clicking Mode
        if fingers[1] == 1 and fingers[2] == 1:
            # 9. Find distance between fingers
            length, img, lineInfo = detector.findDistance(8, 12, img)

            # 10. Click mouse if distance short
            if length < 40:
                cv2.circle(img, (lineInfo[4], lineInfo[5]),
                15, (0, 255, 0), cv2.FILLED)
                autopy.mouse.click()

    # 帧展示逻辑放在判断外,保证无手时也能正常显示画面
    cv2.imshow("Image", img)
    cv2.waitKey(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:06:01