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

Python cvzone开发AR绘画程序无法绘制线条问题求助

故障原因与修复方案

核心问题点

  • 绘制逻辑错误:你将线条绘制在了实时帧画面img上,没有写入持久化的画布imgCanvas,每帧刷新后绘制内容直接丢失,后续合成步骤自然没有线条内容。
  • 触发逻辑错误:当前你设置的绘画触发条件为食指、中指同时抬起,而你没有加双指抬起时的坐标重置逻辑,同时默认的AR绘画逻辑为仅食指抬起时进入绘画状态,双指抬起为暂停选择状态。
  • 颜色参数错误:你设置的画笔颜色drawColor = (0,0,0)是纯黑,和imgCanvas的初始底色完全一致,就算正确绘制到画布上也看不到痕迹。
  • 缩进错误:画布与实时帧的合成代码放在了if hands:的分支内,画面中没有手的时候画布内容不会被合成到显示画面中。

修正后的完整代码

import cv2
import numpy as np
from cvzone.HandTrackingModule import HandDetector
 
brushThickness = 25
# 画笔颜色改为蓝色,避免和画布底色重合
drawColor = (255, 0, 0)
 
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
 
detector = HandDetector(detectionCon=0.65, maxHands=1)
xp, yp = 0, 0
imgCanvas = np.zeros((480, 640, 3), np.uint8)
 
while True:
    # 1. 读取摄像头帧
    success, img = cap.read()
    img = cv2.flip(img, 1)
 
    # 2. 检测手部关键点
    hands, img = detector.findHands(img, flipType=False)
    
    if hands:
        lmList = hands[0]['lmList']
        if len(lmList) != 0:
            # 取食指、中指指尖坐标
            x1, y1 = lmList[8][:2]
            x2, y2 = lmList[12][:2]
    
            # 检测抬起的手指
            fingers = detector.fingersUp(hands[0])

            # 仅食指抬起:进入绘画模式
            if fingers[1] == 1 and fingers[2] == 0:
                cv2.circle(img, (x1, y1), 15, drawColor, cv2.FILLED)
                if xp == 0 and yp == 0:
                    xp, yp = x1, y1
                # 线条绘制到imgCanvas上,而非实时帧img
                cv2.line(imgCanvas, (xp, yp), (x1, y1), drawColor, brushThickness)
                xp, yp = x1, y1
            
            # 食指和中指同时抬起:暂停绘画,重置上一次坐标
            elif fingers[1] == 1 and fingers[2] == 1:
                xp, yp = 0, 0
                cv2.circle(img, (x1, y1), 15, drawColor, cv2.FILLED)
    
            # 所有手指抬起:清空画布
            if all(x == 1 for x in fingers):
                imgCanvas = np.zeros((480, 640, 3), np.uint8)
    
    # 合成逻辑移到if hands外部,保证画布内容始终显示
    imgGray = cv2.cvtColor(imgCanvas, cv2.COLOR_BGR2GRAY)
    _, imgInv = cv2.threshold(imgGray, 50, 255, cv2.THRESH_BINARY_INV)
    imgInv = cv2.cvtColor(imgInv, cv2.COLOR_GRAY2BGR)
    img = cv2.bitwise_and(img, img, imgInv)
    img = cv2.bitwise_or(img, img, imgCanvas)

    cv2.imshow("AR绘画", img)
    # 按q键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:24:00