如何修复cvzone手部检测中ValueError: too many values to unpack错误?
问题:cvzone手部检测中findDistance触发ValueError错误
我编写了结合cvzone手部检测与MCQ展示的Python程序,期望实现食指指尖(lmList[8])与中指指尖(lmList[12])的距离检测,但运行时触发以下错误:
Traceback (most recent call last): File "e:\CODE\.vscode\OpenCV\main.py", line 57, in <module> length, info = detector.findDistance(lmList[0],lmList[12]) File "C:\Users\User1\AppData\Local\Programs\Python\Python310\lib\site-packages\cvzone\HandTrackingModule.py", line 143, in findDistance x1, y1 = p1 ValueError: too many values to unpack (expected 2)
我尝试更换不同版本的mediapipe,问题仍未解决。完整代码如下:
import cv2 as cv import csv from cvzone.HandTrackingModule import HandDetector import cvzone as cvz # Declaring the cap variable to start Camera activity cap = cv.VideoCapture(0) cap.set(3, 1280) cap.set(4, 720) detector = HandDetector(minTrackCon=0.8) # Class to access the elements of Que.csv file via indexing class Questions: def __init__(self, data): self.question = data[0] self.choice1 = data[1] self.choice2 = data[2] self.choice3 = data[3] self.choice4 = data[4] self.answer = int(data[5]) self.userAnswer = None # importing CSV file getFile = 'Que.csv' with open(getFile, newline='\n') as file: reader = csv.reader(file) datafile = list(reader)[1:] # Creating Object for Each mcqList = [] for que in datafile: mcqList.append(Questions(que)) print(len(mcqList)) queNumber = 0 queTotal = len(datafile) while True: ret, frame = cap.read() # To Flip the camera view to the original side hands, frame = detector.findHands(frame, flipType=True) mcq = mcqList[0] frame, box = cvz.putTextRect(frame, mcq.question, [50, 50], 2, 2, offset=15, border=4) frame, box1 = cvz.putTextRect(frame, mcq.choice1, [50, 115], 1, 2, offset=15, border=4) frame, box2 = cvz.putTextRect(frame, mcq.choice2, [150, 115], 1, 2, offset=15, border=4) frame, box3 = cvz.putTextRect(frame, mcq.choice3, [50, 165], 1, 2, offset=15, border=4) frame, box4 = cvz.putTextRect(frame, mcq.choice4, [150, 165], 1, 2, offset=15, border=4) # Checking for a Hand if hands: lmList = hands[0]['lmList'] length, info, frame = detector.findDistance(lmList[8],lmList[12],frame) print(length) cv.imshow('frame', frame) if cv.waitKey(1) & 0xFF == ord('q'): break cap.release() cv.destroyAllWindows()
解决方法
错误原因
lmList中的每个关键点包含x、y、z三个坐标值,而findDistance函数内部尝试将传入的点解包为x和y两个值,直接传入完整的lmList[8]或lmList[12]会因为多了z轴值导致解包失败。
修复步骤
调用findDistance时,仅传入关键点的x和y坐标,忽略z轴数据,修改手部检测部分的代码:
# Checking for a Hand if hands: lmList = hands[0]['lmList'] # 提取每个指尖的x、y坐标(忽略z值) length, info, frame = detector.findDistance(lmList[8][:2], lmList[12][:2], frame) print(length)
额外说明
- 错误日志中写的是
detector.findDistance(lmList[0],lmList[12]),但实际代码用的是lmList[8],确保你取的是食指(索引8)和中指(索引12)的指尖关键点,避免笔误。 findDistance在传入frame参数时会返回三个值:length(距离)、info(包含中点坐标等信息的字典)、frame(绘制了连线的帧),确保接收变量数量匹配。
内容的提问来源于stack exchange,提问作者Roshan
相关产品推荐
相关产品推荐

