The Wayback Machine - https://web.archive.org/web/20240728094725/https://www.geeksforgeeks.org/python-draw-rectangular-shape-and-extract-objects-using-opencv/
Open In App

Draw a rectangular shape and extract objects using Python’s OpenCV

Last Updated : 04 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks.

Let’s see how to draw rectangular shape on image and extract the objects using OpenCV.




# Python program to extract rectangular
# Shape using OpenCV in Python3
import cv2
import numpy as np
  
drawing = False     # true if mouse is pressed
mode = True         # if True, draw rectangle.
ix, iy = -1, -1
  
# mouse callback function
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) & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == 27:
        break
  
cv2.destroyAllWindows() 


Output:

Above piece of code will work with only black background image. But rectangles can be drawn to any images. We can write a program which allows us to select desired portion in an image and extract that selected portion as well. The task includes following things –

  • draw shape on any image
  • re-select the extract portion for in case bad selection
  • extract particular object from the image




# Write Python code here
# import the necessary packages
import cv2
import argparse
  
# now let's initialize the list of reference point
ref_point = []
crop = False
  
def shape_selection(event, x, y, flags, param):
    # grab references to the global variables
    global ref_point, crop
  
    # if the left mouse button was clicked, record the starting
    # (x, y) coordinates and indicate that cropping is being performed
    if event == cv2.EVENT_LBUTTONDOWN:
        ref_point = [(x, y)]
  
    # check to see if the left mouse button was released
    elif event == cv2.EVENT_LBUTTONUP:
        # record the ending (x, y) coordinates and indicate that
        # the cropping operation is finished
        ref_point.append((x, y))
  
        # draw a rectangle around the region of interest
        cv2.rectangle(image, ref_point[0], ref_point[1], (0, 255, 0), 2)
        cv2.imshow("image", image)
  
  
# construct the argument parser and parse the 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 setup the mouse callback function
image = cv2.imread(args["image"])
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", shape_selection)
  
  
# keep looping until the 'q' key is pressed
while True:
    # display the image and wait for a keypress
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF
  
    # press 'r' to reset the window
    if key == ord("r"):
        image = clone.copy()
  
    # if the 'c' key is pressed, break from 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() 


Run : Save the file as capture_events.py and for testing select a demo picture which is located in the same directory. Now, execute the following command –

python capture_events.py --image demo.jpg

Output: First select the desired portion from the image. In addition, we can remove bad selection by pressing ‘r’ as programmed for making a new proper selection.


Fig: Selected Portion

Now after selecting a proper selection like above, just press ‘c’ to extract, as programmed.
Fig: Cut Portion



Previous Article
Next Article

Similar Reads

Draw Shape inside Shape in Python Using Turtle
Prerequisites: Turtle Programming in Python Turtle is a Python feature like a drawing board, which let us command a turtle to draw all over it! We can use many turtle functions which can move the turtle around. Turtle comes in the turtle library. The turtle module can be used in both object-oriented and procedure-oriented ways. Some of the commonly
3 min read
Draw Diamond shape using Turtle graphics in Python
In this article, we are going to learn how to draw the shape of a Diamond using turtle graphics in Python. Turtle graphics: forward(length): moves the pen in the forward direction by x unit.right(angle): rotate the pen in the clockwise direction by an angle x.left(angle): rotate the pen in the anticlockwise direction by an angle x. Approach: Import
2 min read
How to create a semi transparent shape Python-OpenCV
In this article, we will see how to create a semi-transparent shape python OpenCV. Sometimes we need transparency in our outputs. It gives our outputs their own unique style. Today, we will see how you can do it easily with OpenCV python. Here, we are going to cover 3 different methods of shape and they are: Using Rectangular shape.Using Line.and,
4 min read
Find and Draw Contours using OpenCV | Python
Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. Contours come handy in shape analysis, finding the size of the object of interest, and object detection. OpenCV has findContour() function that helps in extracting the contours from the image. It works best on binary images, so
2 min read
Draw Multiple Rectangles in Image using Python-Opencv
In this article, we are going to see how to draw multiple rectangles in an image using Python and OpenCV. Function used:imread(): In the OpenCV, the cv2.imread() function is used to read an image in Python. Syntax: cv2.imread(path_of_image, flag) rectangle(): In the OpenCV, the cv2.rectangle function is used to draw a rectangle on the image in Pyth
2 min read
How to draw Filled rectangle to every frame of video by using Python-OpenCV?
In this article, we will discuss how to draw a filled rectangle on every frame of video through OpenCV in Python. Stepwise Implementation:Import the required libraries into the working space.Read the video on which you have to write. Syntax: cap = cv2.VideoCapture("path") Create an output file using cv2.VideoWriter_fourcc() method. Here you will ha
2 min read
Draw geometric shapes on images using OpenCV
OpenCV provides many drawing functions to draw geometric shapes and write text on images. Let's see some of the drawing functions and draw geometric shapes on images using OpenCV. Some of the drawing functions are : cv2.line() : Used to draw line on an image. cv2.rectangle() : Used to draw rectangle on an image. cv2.circle() : Used to draw circle o
3 min read
Draw a filled polygon using the OpenCV function fillPoly()
fillPoly() function of OpenCV is used to draw filled polygons like rectangle, triangle, pentagon over an image. This function takes inputs of an image and endpoints of Polygon and color. Syntax: cv2.fillpoly(Image,End_Points,Color) Parameter: Image: This is image on which we want draw filled polygonEnd_Points: Points of polygon(for triangle 3 end p
3 min read
Draw a triangle with centroid using OpenCV
Prerequisite: Geometric shapes using OpenCV Given three vertices of a triangle, write a Python program to find the centroid of the triangle and then draw the triangle with its centroid on a black window using OpenCV. Examples: Input: (100, 200) (50, 50) (300, 100) Output: (150, 116) Libraries Needed: OpenCV Numpy Approach: Create a black window wit
2 min read
Detecting objects of similar color in Python using OpenCV
OpenCV is a library of programming functions mainly aimed at real-time computer vision. In this article, we will see how to get the objects of the same color in an image. We can select a color by slide bar which is created by the cv2 command cv2.createTrackbar. Libraries needed:OpenCV NumpyApproach: First of all, we need to read the image which is
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg