【问题标题】:I am having a problem regarding the type error in python. I am trying to create a virtual mouse. I have created a module for it我在 python 中遇到类型错误的问题。我正在尝试创建一个虚拟鼠标。我为它创建了一个模块
【发布时间】:2026-01-26 08:25:01
【问题描述】:

**我正在尝试创建一个虚拟鼠标。我正在使用 opencv-python、mediapipe、time、numpy 等包,还有我自己的包。但似乎有一些错误。你能帮我吗。起初我创建了模块。然后是鼠标本身。但我不明白其中的问题。 ** 我创建的手部跟踪模块

import cv2
import mediapipe as mp
import time


class handDetector():
    def __init__(self, mode=False, maxHands=2, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands,
                                        self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        print(self.results.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)

        return img

    def findPosition(self, img, handNo=0, draw=True):

        lmList = []
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks   [handNo]
            for id, lm in enumerate(myHand.landmark):
                print(id, lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                print(id, cx, cy)
                lmList.append( [ id, cx, cy])
                if draw:
                    cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)

        return lmList


def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(1)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList = detector.findPosition(img)
        if len(lmList) != 0:
            print(lmList[4])

            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)
            if cv2.waitKey(1) == ord("q"):
                break

if __name__ == "__main__":
    main()

这是软件代码

import cv2
import cvzone.HandTrackingModule
import numpy as np
import HandTrackingModule as htm
import time
import autopy

##########################
wCam, hCam = 640, 480
frameR = 100  # Frame Reduction
smoothening = 7
#########################

pTime = 0
plocX, plocY = 0, 0
clocX, clocY = 0, 0

cap = cv2.VideoCapture(1)
cap.set(3, wCam)
cap.set(4, hCam)
detector = htm.handDetector()
wScr, hScr = autopy.screen.size()
# print(wScr, hScr)

while True:
    # 1. Find hand Landmarks
    success, img = cap.read()
    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img)
    # 2. Get the tip of the index and middle fingers
    if len(lmList) != 0:
        x1, y1 = lmList [8][1:]
        x2, y2 = lmList [12][1:]
        # print(x1, y1, x2, y2)

    # 3. Check which fingers are up
    fingers = cvzone.HandTrackingModule.HandDetector.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)
        print(length)
        # 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()

            # 11. Frame Rate
            cTime = time.time()
            fps = 1 / (cTime - pTime)
            pTime = cTime
            cv2.putText(img, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3,
                        (255, 0, 0), 3)
            # 12. Display
            cv2.imshow("Image", img)
            cv2.waitKey(1)

错误:

lmList, bbox = detector.findPosition(img)
ValueError: not enough values to unpack (expected 2, got 0)

请帮帮我。这是软件代码。我正在尝试使用这些包创建虚拟鼠标,并且我自己创建了一个模块。但似乎有一些错误。我希望你能帮忙。愿上帝保佑帮助者

【问题讨论】:

    标签: python package


    【解决方案1】:

    函数detector.findPosition 返回一个列表lmList,但在主脚本中调用时,它的输出被分配(并解压缩)给两个变量lmListbbox。所以函数需要输出两个值,而不仅仅是一个:

    def findPosition(self, img, handNo=0, draw=True):
        # Do something to produce lmList and bbox...
        return lmList, bbox
    

    如果您只对列表输出感兴趣,您可以随时这样做:

    lmList, _ = detector.findPosition(img)
    

    【讨论】:

    • 感谢您的建议。你能在编辑后穿上整个代码吗?这样就可以了。谢谢。
    • 不客气。我会,但我不知道你想如何定义 bbox (即那是什么);你能提供更多的上下文吗?
    最近更新 更多