Draw a rectangular shape and extract objects using Python\'s OpenCV

OpenCV is an Open Source Computer Vision Library in Python. It provides numerous functions to perform various image and video processing operations. The library uses the NumPy module to represent all video frames and images as ndarray types.

In this article, we will see different ways to draw rectangular shapes and extract objects using Python OpenCV.

Drawing a Rectangle

To draw a rectangular shape on an image, Python OpenCV provides the cv2.rectangle() method. Following is the syntax ?

Syntax

cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])

Parameters

  • img: The source image where to draw the rectangle

  • pt1: Coordinates of the top-left corner (x1, y1)

  • pt2: Coordinates of the bottom-right corner (x2, y2)

  • color: Rectangle color in BGR format

  • thickness: Line thickness (default is 1)

pt1(x1,y1) pt2(x2,y2)

Using Pre-defined Coordinates

In this approach, we define the rectangle coordinates manually and extract the object from that area ?

Example

import cv2
import numpy as np

# Create a sample image
img = np.ones((400, 600, 3), dtype=np.uint8) * 255  # White background
cv2.rectangle(img, (100, 100), (300, 200), (128, 128, 128), -1)  # Gray rectangle
cv2.circle(img, (200, 150), 30, (255, 0, 0), -1)  # Blue circle

# Define rectangle coordinates
top_left = (80, 80)
bottom_right = (320, 220)

# Draw rectangle
color = (0, 255, 0)  # Green color
thickness = 2
cv2.rectangle(img, top_left, bottom_right, color, thickness)

# Extract object from rectangular area
# Note: For array slicing, use [y1:y2, x1:x2] format
rect_area = img[top_left[1]:bottom_right[1], top_left[0]:bottom_right[0]]

print("Original image shape:", img.shape)
print("Extracted area shape:", rect_area.shape)
Original image shape: (400, 600, 3)
Extracted area shape: (140, 240, 3)

Using Mouse Events for Interactive Selection

OpenCV provides mouse event handlers for interactive rectangle drawing. Key mouse events include ?

  • cv2.EVENT_LBUTTONDOWN: Left mouse button pressed

  • cv2.EVENT_LBUTTONUP: Left mouse button released

The setMouseCallback() Function

This function sets a mouse event handler for a specific window ?

cv2.setMouseCallback(winname, onMouse, userdata)

Parameters

  • winname: Name of the window

  • onMouse: Callback function for mouse events

  • userdata: Optional parameter passed to callback

Example

import cv2
import numpy as np

# Global variables
drawing = False
top_left_pt = ()
bottom_right_pt = ()

def draw_rectangle(event, x, y, flags, param):
    global drawing, top_left_pt, bottom_right_pt, img, img_copy
    
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        top_left_pt = (x, y)
    
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            img_copy = img.copy()
            cv2.rectangle(img_copy, top_left_pt, (x, y), (0, 255, 0), 2)
            cv2.imshow("Image", img_copy)
    
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        bottom_right_pt = (x, y)
        cv2.rectangle(img, top_left_pt, bottom_right_pt, (0, 255, 0), 2)
        cv2.imshow("Image", img)

# Create sample image
img = np.ones((400, 600, 3), dtype=np.uint8) * 255
cv2.rectangle(img, (150, 100), (450, 250), (200, 200, 200), -1)
cv2.circle(img, (300, 175), 40, (255, 100, 100), -1)

img_copy = img.copy()

cv2.namedWindow("Image")
cv2.setMouseCallback("Image", draw_rectangle)

print("Draw rectangle by clicking and dragging. Press 'c' to crop, 'r' to reset, 'q' to quit.")

while True:
    cv2.imshow("Image", img)
    key = cv2.waitKey(1) & 0xFF
    
    if key == ord('r'):
        img = img_copy.copy()
    elif key == ord('c'):
        if top_left_pt and bottom_right_pt:
            cropped = img_copy[top_left_pt[1]:bottom_right_pt[1], 
                             top_left_pt[0]:bottom_right_pt[0]]
            cv2.imshow("Cropped", cropped)
    elif key == ord('q'):
        break

cv2.destroyAllWindows()

Comparison

Method Use Case Advantages Disadvantages
Pre-defined coordinates Automated processing Fast, reproducible Not flexible
Mouse events Interactive selection User-friendly, flexible Manual input required

Key Points

  • Array slicing for extraction uses [y1:y2, x1:x2] format

  • Rectangle coordinates are (x, y) format

  • Mouse callbacks enable interactive rectangle drawing

  • Always create a copy of the original image for reset functionality

Conclusion

OpenCV provides flexible methods for drawing rectangles and extracting objects. Use pre-defined coordinates for automated processing or mouse events for interactive selection. Remember to use proper array slicing format for object extraction.

Updated on: 2026-03-27T06:53:31+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements