Python | Draw rectangular shape and extract objects using OpenCV



Let`s see how to draw a rectangular shape on an image and extract objects using OpenCV.

# Python program to extract the rectangle
# Form using OpenCV in Python3

import cv2

import numpy as np

  

drawing = False   # true if the mouse is pressed

mode = True   # if True, draw a rectangle.

ix, iy = - 1 , - 1

  
# mouse callback

def draw_circle (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.rectangle (img, (ix, iy), (x, y), ( 0 , 255 , 0 ), 3 )

a = x

b = y

  if a! = x | b! = y:

cv2.rectangle (img, (ix, iy), (x, y), ( 0 , 0 , 0 ), - 1 )

else :

cv2.circle (img, (x, y), 5 , ( 0 , 0 , 255 ), - 1 )

  

  elif event = = cv2.EVENT_LBUTTONUP:

drawing = False

if mode = = True :

cv2.rectangle (img, (ix, iy), (x, y), ( 0 , 255 , 0 ), 2 )

  

else :

cv2.circle (img, (x, y), 5 , ( 0 , 0 , 255 ), - 1 )

  

img = np.zeros ( ( 512 , 512 , 3 ), np.uint8)

cv2.namedWindow ( ` image` )

cv2.setMouseCallback ( ` image` , draw_circle)

 

while ( 1 ):

  cv2 .imshow ( `image` , img)

  k = cv2.waitKey ( 1 ) & amp;  0xFF

if k = = ord ( `m` ):

mode = not mode

elif k = = 27 :

break

 
cv2.destroyAllWindows () 

Exit:

The above piece of code will only work with a black background image. But rectangles can be drawn on any images. We can write a program that allows us to select the desired portion of the image and extract that selected portion. The task includes the following things —

  • draw a shape on any image
  • re-select part of the extract in case of unsuccessful selection
  • retrieve a specific object from image

# Write Python code here
# import required packages

import cv2

import argparse

 
# now let`s initialize the pivot point list

ref_point = []

crop = False

 

def shape_selection (event, x, y, flags, param):

# grab references to global variables

global ref_point, crop

  

# if the left mouse button was pressed, write down the initial

# (x, y) coordinates and indicate that clipping is in progress

  if event = = cv2.EVENT_LBUTTONDOWN:

ref_point = [(x, y)]

 

# check if the left mouse button was released

elif event = = cv2.EVENT_LBUTTONUP:

# write down end (x, y) coordinates and indicate that

# trim operation completed

ref_point.append ((x, y))

 

# draw a rectangle around the ROI

 cv2.rectangle (image, ref_point [ 0 ], ref_point [ 1 ], ( 0 , 255 , 0 ), 2 )

cv2.imshow ( " image " , image)

 

 
# build argument parser and parse arguments

ap = argparse.ArgumentParser ()

ap.add_argument ( "- i" , "- image" , required = True , help = "Path to the image" )

args = vars (ap.parse_args ())

  
# load the image, clone it and configure the mouse callback

image = cv2.imread (args [ " image " ] )

clone = image.copy ( )

cv2.namedWindow ( "image" )

cv2.setMouseCallback ( "image" , shape_selection)

 

 
# continue the loop until the key is pressed & # 39; q & # 39;

while True :

# display the image and wait for a key press

cv2.imshow ( "image " , image)

  key = cv2.waitKey ( 1 ) & amp;  0xFF

 

# press & # 39; r & # 39; to reset the window

  if key = = ord ( "r" ):

image = clone.copy ()

 

# if the & # 39; c & # 39; key is pressed, break out of the loop

elif key = = ord ( "c" ):

break

 

if len (ref_point) = = 2 :

crop_img = clone [ref_point [ 0 ] [ 1 ]: ref_point [ 1 ] [ 1 ], ref_point [ 0 ] [ 0 ]:

ref_point [ 1 ] [ 0 ]]

cv2.imshow ( "crop_img" , crop_img)

cv2.waitKey ( 0 )

 
# close all open windows
cv2.destroyAllWindows () 

Execute : save the file as capture_events.py and for testing select a demo picture located in the same directory. Now run the following command —

 python capture_events.py --image demo.jpg 

Output : First select the part of the image you want. Alternatively, we can remove the incorrect selection by pressing "r" as programmed to create a new correct selection.


Fig: Selected part

Now after choosing the correct selection as above, just press" c "to extract as programmed. 
Fig: Cut part