To apply boundary fill in a region i need to draw a free hand shape(random) using mouse in python-opencv
You asked how to draw any giver random shape on a picture using your computer's mouse. Here is a simple solution:
First, you will need to design a method that enables you to draw. So let's inspire ourselves from OpenCV: Mouse as a Paint-Brush where a method is used to draw common regular shapes such as a circle or a rectangle using a mouse. In your case, you will need random drawing as you could do with your hand.
So using that method you can draw points using the mouse and perform an interpolation between them using cv2.line()
method:
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
Where im
is the image you read and while you must memorize the former coordinates of the mouse position all the time:
current_former_x = former_x
current_former_y = former_y
Full OpenCV program:
Here is the code. Do not hesitate to comment anything you wouldn't understand:
'''
Created on Apr 3, 2016
@author: Bill BEGUERADJ
'''
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 begueradj_draw(event,former_x,former_y,flags,param):
global current_former_x,current_former_y,drawing, mode
if event==cv2.EVENT_LBUTTONDOWN:
drawing=True
current_former_x,current_former_y=former_x,former_y
elif event==cv2.EVENT_MOUSEMOVE:
if drawing==True:
if mode==True:
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
current_former_x = former_x
current_former_y = former_y
#print former_x,former_y
elif event==cv2.EVENT_LBUTTONUP:
drawing=False
if mode==True:
cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
current_former_x = former_x
current_former_y = former_y
return former_x,former_y
im = cv2.imread("darwin.jpg")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',begueradj_draw)
while(1):
cv2.imshow('Bill BEGUERADJ OpenCV',im)
k=cv2.waitKey(1)&0xFF
if k==27:
break
cv2.destroyAllWindows()
Demo:
former_x
and former_y
because they are reused over and over as long as you draw. Try to run the program –
Adamson This example from the opencv sample directory allows you to draw an arbitrary rectangle in an image and select the ROI:
https://github.com/Itseez/opencv/blob/master/samples/python/mouse_and_match.py
You can easily add alternatives to draw circles or polygons instead, e.g. by pressing a letter first.
© 2022 - 2024 — McMap. All rights reserved.