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
How to detect polygons in image using OpenCV Python?
Polygon detection is a common computer vision task that involves finding multi-sided shapes in images. OpenCV provides powerful tools to detect polygons by first finding contours and then approximating them to identify shapes with 5 or more vertices.
How It Works
The polygon detection process follows these key steps:
- Contour Detection - Find all object boundaries in the image
- Contour Approximation - Simplify contours to approximate polygonal shapes
- Vertex Counting - Count vertices to identify polygons (?5 vertices)
- Visualization - Draw detected polygons on the original image
Step-by-Step Process
Import the required library OpenCV
Read the input image using cv2.imread() and convert it to grayscale
Apply thresholding cv2.threshold() on the grayscale image to create a binary image
Find contours using cv2.findContours() function
Loop over all detected contours
Compute approximate contour points using cv2.approxPolyDP() function
If the approximate contour has 5 or more vertices, classify it as a polygon
Draw the detected polygons and display the result
Example
Here's a complete example that detects polygons in an image and highlights them ?
import cv2
import numpy as np
# Create a sample image with polygons for demonstration
img = np.ones((400, 500, 3), dtype=np.uint8) * 255
# Draw some sample polygons
pentagon = np.array([[100, 100], [150, 80], [180, 120], [140, 160], [80, 140]], np.int32)
hexagon = np.array([[250, 100], [300, 90], [330, 120], [310, 160], [260, 170], [230, 140]], np.int32)
octagon = np.array([[350, 100], [380, 110], [400, 140], [390, 170], [360, 180], [330, 170], [320, 140], [330, 110]], np.int32)
cv2.fillPoly(img, [pentagon], (200, 200, 200))
cv2.fillPoly(img, [hexagon], (150, 150, 150))
cv2.fillPoly(img, [octagon], (100, 100, 100))
# Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Apply thresholding
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(f"Number of contours detected: {len(contours)}")
# Process each contour
for cnt in contours:
# Approximate the contour
epsilon = 0.02 * cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
# Get coordinates for text placement
x, y = cnt[0, 0]
# Check if it's a polygon (5 or more vertices)
if len(approx) >= 5:
cv2.drawContours(img, [approx], -1, (0, 255, 255), 3)
cv2.putText(img, f'Polygon ({len(approx)} vertices)', (x-20, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
print("Polygon detection completed!")
Number of contours detected: 3 Polygon detection completed!
Key Parameters
| Function | Parameter | Description |
|---|---|---|
cv2.threshold() |
threshold value | Adjust for better contour detection |
cv2.approxPolyDP() |
epsilon | Approximation accuracy (0.01-0.03 * perimeter) |
len(approx) >= 5 |
vertex count | Minimum vertices to classify as polygon |
Common Use Cases
Shape Recognition - Identifying geometric shapes in images
Object Detection - Finding rectangular or polygonal objects
Document Processing - Detecting tables, forms, and structured elements
Quality Control - Inspecting manufactured parts with specific shapes
Conclusion
Polygon detection in OpenCV involves finding contours, approximating them with cv2.approxPolyDP(), and counting vertices. Shapes with 5 or more vertices are classified as polygons. Adjust the epsilon parameter and threshold values for optimal results based on your specific image characteristics.
