Home > database >  Multiple overlapping rectangle being drawn over an image when using cv2 to draw using mouse
Multiple overlapping rectangle being drawn over an image when using cv2 to draw using mouse

Time:01-03

I was trying to draw rectangles using mouse over an image, using openCV package in python. When ever I drew a rectangle, I got multiple rectangles overlapping one another, instead of a single rectangle. Like the below image

the output that I got

Here is my code. Please tell me where I went wrong and what needs to be corrected, so that I get only 1 rectangle.

import cv2
import numpy as np

drawing  = False
ix,iy = -1, -1
img = cv2.imread('drawing_over_image/dog.jpg')
def draw(event, x, y, flags, params):

    global ix, iy, drawing

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

    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            if ix < x and iy < y:
                cv2.rectangle(img=img, pt1=(ix,iy), pt2=(x,y), color=[255,0,0], thickness=1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        cv2.rectangle(img=img, pt1=(ix,iy), pt2=(x,y), color=[255,0,0], thickness=1)


if __name__ == "__main__":
    
    while True:
        cv2.imshow(winname='image', mat=img)
        cv2.setMouseCallback('image', draw)

        if cv2.waitKey(1) & 0xFF == 27:
            cv2.destroyAllWindows()
            break

    

CodePudding user response:

Its drawing multiple rectangles because you are drawing rectangles on every mouse move after user is pressing on the button. Instead you should draw whenever the event is done namely when the user release the left button. I fixed your code and add a basic ref image for you to see your rectangle when you are drawing. Hope it helps!

import cv2
import numpy as np

drawing  = False
ix,iy = -1, -1
img = cv2.imread('drawing_over_image/dog.jpg')
refimg = img.copy()
def draw(event, x, y, flags, params):

    global ix, iy, drawing

    if event == cv2.EVENT_LBUTTONDOWN:
        ix,iy = x,y
        drawing = True
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            if ix < x and iy < y:
                cv2.rectangle(img=refimg, pt1=(ix,iy), pt2=(x,y), color=[255,0,0], thickness=1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        if ix < x and iy < y:
            cv2.rectangle(img=img, pt1=(ix,iy), pt2=(x,y), color=[255,0,0], thickness=1)



if __name__ == "__main__":
    
    while True:
        cv2.imshow(winname='image', mat=refimg)
        cv2.setMouseCallback('image', draw)
        refimg = img.copy()
        if cv2.waitKey(1) & 0xFF == 27:
            cv2.destroyAllWindows()
            break

Output: enter image description here

CodePudding user response:

Comment out line 27. And move to line 24

cv2.setMouseCallback('image', draw)
if __name__ == "__main__":
  • Related