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

使用OpenCV与MediaPipe开发手部追踪模块遇AttributeError求助

解决AttributeError: 'handDetector' object has no attribute 'hands'错误

核心问题

你的handDetector类构造函数名称错误,Python要求类的构造函数必须是__init__(前后各两个下划线),你写的是init,导致初始化代码完全没执行,self.hands根本没被创建,调用findHands时自然会触发属性不存在的错误。

其他需要修复的小问题

  1. findHands方法中,遍历手部关键点时错误使用了self.result,应该用局部变量result
  2. 创建Hands实例时,没有传入你定义的参数(mode、maxHands等),导致这些参数设置无效

修复后的完整代码

import cv2
import mediapipe as mp
import time


class handDetector():
    # 修正构造函数名称为__init__
    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
        # 传入自定义参数到Hands实例
        self.hands = self.mpHands.Hands(
            static_image_mode=self.mode,
            max_num_hands=self.maxHands,
            model_complexity=self.modelC,
            min_detection_confidence=self.detectionCon,
            min_tracking_confidence=self.trackCon
        )
        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:
            # 修正为使用局部变量result
            for handLms in 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()

修改说明

  • 把def init(改成def __init__(,确保类实例化时自动执行初始化逻辑,创建self.hands属性
  • 在Hands()实例化时传入你定义的参数,让你的配置生效
  • 把self.result.multi_hand_landmarks改成result.multi_hand_landmarks,因为result是方法内的局部变量,不是类的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:20:30