Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Draw Multiple Rectangles in Image using OpenCV Python
OpenCV is an Open Source Computer Vision Library in Python that provides numerous functions to perform various image and video processing operations. In this article, we will explore different ways to draw multiple rectangles in an image using OpenCV Python.
To draw rectangular shapes on an image, OpenCV provides the cv2.rectangle() method which can be used in various approaches to create multiple rectangles efficiently.
The cv2.rectangle() Function
The cv2.rectangle() method draws rectangular shapes on an image. Following is the syntax ?
cv2.rectangle(img, pt1, pt2, color[, thickness[, lineType[, shift]]])
Parameters
img: The source image where to draw the rectangle
pt1: Top-left corner coordinates (x, y) of the rectangle
pt2: Bottom-right corner coordinates (x, y) of the rectangle
color: Rectangle color in BGR format
thickness: Line thickness of the rectangle border (default: 1)
Method 1: Using Pre-defined Coordinates
In this approach, we manually define the coordinates for each rectangle using a list of coordinate pairs.
Example
Here we use a list of coordinate pairs to draw multiple rectangles around specific areas ?
import cv2
import numpy as np
# Create a sample image for demonstration
img = np.ones((400, 600, 3), dtype=np.uint8) * 255
# Define rectangle coordinates as [top-left, bottom-right] pairs
rectangles = [
[(50, 50), (150, 120)],
[(200, 80), (350, 180)],
[(400, 100), (550, 200)],
[(100, 250), (250, 350)]
]
# Draw rectangles with different colors
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0)]
thickness = 2
for i, (pt1, pt2) in enumerate(rectangles):
color = colors[i % len(colors)]
cv2.rectangle(img, pt1, pt2, color, thickness)
print("Multiple rectangles drawn successfully")
Multiple rectangles drawn successfully
Method 2: Using Dictionary with Normalized Coordinates
This method uses normalized coordinates (0-1 range) which can be scaled to any image size ?
import cv2
import numpy as np
# Create a sample image
img = np.ones((400, 600, 3), dtype=np.uint8) * 255
img_h, img_w = img.shape[:2]
# Define objects with normalized coordinates
objects = {
'object1': {'center_x': 0.25, 'center_y': 0.3, 'width': 0.2, 'height': 0.25},
'object2': {'center_x': 0.75, 'center_y': 0.3, 'width': 0.15, 'height': 0.2},
'object3': {'center_x': 0.5, 'center_y': 0.7, 'width': 0.3, 'height': 0.2}
}
# Convert normalized coordinates to pixel coordinates
for obj_name, coords in objects.items():
center_x = coords['center_x']
center_y = coords['center_y']
width = coords['width']
height = coords['height']
# Calculate corner points
x_min = int((center_x - width/2) * img_w)
y_min = int((center_y - height/2) * img_h)
x_max = int((center_x + width/2) * img_w)
y_max = int((center_y + height/2) * img_h)
# Draw rectangle
cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)
print("Rectangles drawn using normalized coordinates")
Rectangles drawn using normalized coordinates
Method 3: Using cv2.findContours() for Object Detection
This method automatically detects objects in binary images and draws bounding rectangles around them ?
import cv2
import numpy as np
# Create a binary image with white circles on black background
img = np.zeros((300, 400), dtype=np.uint8)
cv2.circle(img, (100, 100), 30, 255, -1)
cv2.circle(img, (250, 150), 25, 255, -1)
cv2.circle(img, (350, 200), 20, 255, -1)
# Convert to color image for rectangle drawing
result = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
# Find contours
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw bounding rectangles around each contour
for contour in contours:
x, y, w, h = cv2.boundingRect(contour)
cv2.rectangle(result, (x, y), (x+w, y+h), (0, 255, 0), 2)
print(f"Found {len(contours)} objects and drew bounding rectangles")
Found 3 objects and drew bounding rectangles
Comparison of Methods
| Method | Use Case | Advantages | Disadvantages |
|---|---|---|---|
| Pre-defined Coordinates | Manual annotation | Precise control, simple | Manual effort required |
| Normalized Coordinates | Scalable annotations | Resolution independent | Still requires manual setup |
| Contour Detection | Automatic detection | No manual coordinates needed | Works only on binary images |
Conclusion
OpenCV provides flexible methods to draw multiple rectangles on images. Use pre-defined coordinates for precise manual control, normalized coordinates for scalable applications, and contour detection for automatic object detection in binary images.
