OpenCV:如何用鼠标连续绘制?

OpenCV: how to draw continously with a mouse?

我修改了一个取自 OpenCV 文档的简单程序。

我只是想用鼠标指针连续画画。目前我成功地画了,但不是连续的,除非我鼠标移动得太慢。

代码:

import cv2
import numpy as np 

drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve

# mouse callback function
def interactive_drawing(event,x,y,flags,param):
    global ix,iy,drawing, mode

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        ix,iy=x,y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.circle(img,(x,y),1,(0,0,255),-1)
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.circle(img,(x,y),1,(0,0,255),-1)        


img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('Window')
cv2.setMouseCallback('Window',interactive_drawing)
while(1):
    cv2.imshow('Window',img)
    k=cv2.waitKey(1)&0xFF
    if k==27:
        break
cv2.destroyAllWindows()

希望这张截图能解释我的问题:细线看起来是连续的,因为我移动鼠标光标的速度太慢了。较长的线不是连续的,因为我必须以正常速度移动光标:

我希望能像这样连续画画:

谁能告诉我如何解决这个问题? 提前谢谢你。

与其为回调函数的每次调用绘制单个圆圈,不如尝试从最后一个点到当前点绘制一条线。
因此,您必须将最后一个点存储在全局变量中。

OpenCV 已经在 python 的示例中实现了这样的功能。它被称为Sketcher

有一个很好的示例演示了如何将其用于 inpainting

试试这个:

import cv2
import numpy as np 

drawing = False # true if mouse is pressed
pt1_x , pt1_y = None , None

# mouse callback function
def line_drawing(event,x,y,flags,param):
    global pt1_x,pt1_y,drawing

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        pt1_x,pt1_y=x,y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            cv2.line(img,(pt1_x,pt1_y),(x,y),color=(255,255,255),thickness=3)
            pt1_x,pt1_y=x,y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        cv2.line(img,(pt1_x,pt1_y),(x,y),color=(255,255,255),thickness=3)        


img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('test draw')
cv2.setMouseCallback('test draw',line_drawing)

while(1):
    cv2.imshow('test draw',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()