Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a free hand shape(random) on an image in python using opencv

Tags:

python

opencv

To apply boundary fill in a region i need to draw a free hand shape(random) using mouse in python-opencv

like image 483
Neenu Avatar asked Apr 03 '16 04:04

Neenu


1 Answers

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:

enter image description here

like image 62
Billal Begueradj Avatar answered Sep 28 '22 10:09

Billal Begueradj