opencv 属性错误:'handDetector'对象没有'hands'属性

2skhul33  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(521)

我尝试使用opencv和mediapipe编写手跟踪模块程序,但遇到了此错误。有人能帮助我吗?我使用的是opencv版本:4.6.0.66,媒体管道版本:0.8.11,以及Python版本:3.7

import cv2
import mediapipe as mp
import time

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

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands()
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        result = self.hands.process(imgRGB)
        #print(result.multi_hand_landmarks)
        if result.multi_hand_landmarks:
            for handLms in self.result.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)
        return img

def main():
    ctime = 0;
    ptime = 0;
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)

        ctime = time.time()
        fps = 1 / (ctime - ptime)
        ptime = ctime

        cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 255), 3)
        cv2.imshow("Image", img)
        cv2.waitKey(1)

if __name__ == "__main__":
    main()

我遇到了这个错误。它说hands属性不是handDetector类的一部分:

Traceback (most recent call last):
  File "/Users/ritessshhh/PycharmProjects/handtracking/main.py", line 48, in <module>
    main()
  File "/Users/ritessshhh/PycharmProjects/handtracking/main.py", line 36, in main
    img = detector.findHands(img)
  File "/Users/ritessshhh/PycharmProjects/handtracking/main.py", line 20, in findHands
    result = self.hands.process(imgRGB)
AttributeError: 'handDetector' object has no attribute 'hands'
w7t8yxp5

w7t8yxp51#

在Python中,默认的构造函数名为__init__(而不是init)。尝试将handDetector类的构造函数重命名为__init__
(Also,将handDetector类别重新命名为HandDetector可能是个好主意,以便将它(ClassName)与regularVariable区分开来。)

相关问题