Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenCV: how to draw continously with a mouse?

I modified a simple program taken from OpenCV documentation.

I simply want to draw using the mouse pointer continuously. For the moment I succeeded to draw, but not in a continuous way unless if I move too slowly the mouse cursor.

Code:

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()

Hopefully this screenshot explains my problem: the small line looks continuous because I had to move the mouse cursor too slowly. The longer line, is not continuous because I had to move the cursor with the normal speed:

enter image description here

I expect to be able to draw continuously like this:

enter image description here

Any one could show how to resolve this problem ? Thank you in advance.

like image 557
user4519127 Avatar asked Oct 23 '25 20:10

user4519127


1 Answers

Try this :

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()
like image 105
Abhishek Kumar Avatar answered Oct 25 '25 11:10

Abhishek Kumar