How to compute the aspect ratio of an object in an image using OpenCV Python?

The aspect ratio of an object is computed as the ratio between the width and height of its bounding rectangle. To calculate this, we first find the bounding rectangle using OpenCV's cv2.boundingRect() function.

Syntax

x, y, w, h = cv2.boundingRect(contour)
aspect_ratio = float(w) / h

Here, contour is a numpy array containing the contour points of an object in the image.

Step-by-Step Process

Follow these steps to compute the aspect ratio of objects in an image:

1. Import Required Libraries

import cv2
import numpy as np

2. Load and Preprocess Image

# Create a simple test image with a rectangle
img = np.zeros((300, 400, 3), dtype=np.uint8)
cv2.rectangle(img, (50, 80), (200, 150), (255, 255, 255), -1)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print("Image shape:", gray.shape)
Image shape: (300, 400)

3. Create Binary Image and Find Contours

# Apply thresholding
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Number of objects detected:", len(contours))
Number of objects detected: 1

Example 1: Single Object Aspect Ratio

This example demonstrates computing the aspect ratio of a single object ?

import cv2
import numpy as np

# Create a test image with a rectangle
img = np.zeros((300, 400, 3), dtype=np.uint8)
cv2.rectangle(img, (50, 80), (200, 150), (255, 255, 255), -1)

# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply thresholding
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Define function to compute aspect ratio
def compute_aspect_ratio(contour):
    x, y, w, h = cv2.boundingRect(contour)
    return float(w) / h

# Select first contour and compute aspect ratio
if contours:
    cnt = contours[0]
    aspect_ratio = compute_aspect_ratio(cnt)
    aspect_ratio = round(aspect_ratio, 2)
    
    # Draw contour and bounding rectangle
    cv2.drawContours(img, [cnt], -1, (0, 255, 0), 2)
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    
    # Add text
    cv2.putText(img, f'AR: {aspect_ratio}', (x, y-10), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)
    
    print(f"Aspect Ratio: {aspect_ratio}")
    print(f"Width: {w}, Height: {h}")
Aspect Ratio: 2.14
Width: 150, Height: 70

Example 2: Multiple Objects

This example shows how to compute aspect ratios for multiple objects in an image ?

import cv2
import numpy as np

# Create test image with multiple shapes
img = np.zeros((400, 500, 3), dtype=np.uint8)

# Add different shapes
cv2.rectangle(img, (50, 50), (150, 100), (255, 255, 255), -1)  # Rectangle
cv2.circle(img, (300, 75), 40, (255, 255, 255), -1)           # Circle
cv2.rectangle(img, (100, 200), (200, 350), (255, 255, 255), -1) # Tall rectangle

# Convert to grayscale and find contours
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print(f"Number of objects detected: {len(contours)}")

# Function to compute aspect ratio
def compute_aspect_ratio(contour):
    x, y, w, h = cv2.boundingRect(contour)
    return float(w) / h

# Process all contours
for i, cnt in enumerate(contours):
    # Compute aspect ratio
    aspect_ratio = compute_aspect_ratio(cnt)
    aspect_ratio = round(aspect_ratio, 2)
    
    # Get bounding rectangle
    x, y, w, h = cv2.boundingRect(cnt)
    
    # Draw contour and bounding rectangle
    cv2.drawContours(img, [cnt], -1, (0, 255, 0), 2)
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    
    # Add aspect ratio text
    cv2.putText(img, f'{aspect_ratio}', (x, y-10), 
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
    
    print(f"Object {i+1}: Aspect Ratio = {aspect_ratio}")
Number of objects detected: 3
Object 1: Aspect Ratio = 2.0
Object 2: Aspect Ratio = 1.0
Object 3: Aspect Ratio = 0.67

Interpreting Aspect Ratios

Understanding what aspect ratios mean:

Aspect Ratio Shape Description Example
> 1.0 Wider than tall Horizontal rectangles, ellipses
= 1.0 Equal width and height Squares, circles
< 1.0 Taller than wide Vertical rectangles, ellipses

Key Points

? The cv2.boundingRect() function returns the smallest rectangle that completely encloses the contour

? Aspect ratio is calculated as width divided by height of the bounding rectangle

? Use float(w)/h to ensure floating-point division

? Filter contours by area before computing aspect ratios to ignore noise

Conclusion

Computing aspect ratios helps classify and analyze object shapes in computer vision applications. Use cv2.boundingRect() to get dimensions, then divide width by height for the aspect ratio. This metric is useful for shape recognition and object filtering.

Updated on: 2026-03-26T22:09:11+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements