使用OpenCV开发手势鼠标时遭遇ValueError问题求助
解决cvzone HandDetector的ValueError问题
问题原因
你遇到的ValueError: not enough values to unpack (expected 2, got 1),核心是cvzone官方的HandDetector模块与你自定义的HandTrackingModule返回的关键点列表结构完全不同:
- 自定义模块的
lmlist每个元素格式是[关键点ID, x坐标, y坐标],所以你用lmlist[8][1:]能取出x、y两个值; - 而cvzone的
findPosition()方法默认返回的lmlist,每个元素直接是[x坐标, y坐标],没有关键点ID字段,此时lmlist[8][1:]只会取出y坐标一个值,自然无法解包给两个变量。
修复步骤
1. 修改坐标解包逻辑
把原来的坐标提取代码:
x1,y1 = lmlist[8][1:] x2,y2 = lmlist[12][1:]
直接改为:
x1,y1 = lmlist[8] x2,y2 = lmlist[12]
2. 修复其他隐性错误
代码里还有两个未处理的问题:
- 使用了
np.interp但未导入numpy库; - 调用了
mouse.move()但未初始化鼠标控制器对象。
需要补充以下代码:
# 补充导入语句 import numpy as np from pynput.mouse import Controller # 在初始化detector后添加鼠标对象初始化 mouse = Controller()
完整修复后的代码
import cv2 from cvzone.HandTrackingModule import HandDetector import keyboard import time from pynput.keyboard import Controller from pynput.mouse import Controller import datetime import pyautogui import numpy as np wcam, hcam = 640, 480 framer = 150 cap = cv2.VideoCapture(0) cap.set(3, wcam) cap.set(4, hcam) ptime = 0 detector = HandDetector(detectionCon=0.8, maxHands=2) wsc, hsc = pyautogui.size() mouse = Controller() # 初始化鼠标控制器 print(wsc, hsc) while True: success, img = cap.read() img = detector.findHands(img) lmlist, bbox = detector.findPosition(img) if len(lmlist) != 0: x1, y1 = lmlist[8] # 直接解包x,y坐标 x2, y2 = lmlist[12] print(x1, x2, y1, y2) fingers = detector.fingerUp() cv2.rectangle(img, (framer, framer), (wcam - framer, hcam - framer), 0, 2) if fingers[1] == 1 and fingers[2] == 0: x3 = np.interp(x1, (framer, wcam - framer), (0, wsc)) y3 = np.interp(y1, (framer, hcam - framer), (0, hsc)) mouse.move(x3, y3) if fingers[1] == 1 and fingers[2] == 1: length, img, _ = detector.findDistance(8, 12, img) print(length) ctime = time.time() fps = 1 / (ctime - ptime) ptime = ctime cv2.putText(img, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3, 0, 5) cv2.imshow("window", img) cv2.waitKey(1)
内容的提问来源于stack exchange,提问作者Akshit Singh
相关产品推荐
相关产品推荐

