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 check if an image contour is convex or not in OpenCV Python?
The function cv2.isContourConvex() is used to check whether a curve (contour) is convex or not. A contour of an object in the image is a curve joining all the continuous points along the boundary, having the same color or intensity. Contours are used for shape analysis and object detection and recognition.
Syntax
The syntax for cv2.isContourConvex() is ?
cv2.isContourConvex(cnt)
Where, "cnt" is a numpy array of the contour points of an object in the image. It returns True if the contour cnt is convex, else False.
Understanding Convex vs Non-Convex Shapes
A shape is convex if all interior angles are less than 180 degrees and any line drawn between two points inside the shape lies entirely within the shape. Rectangles, circles, and triangles are convex shapes. A shape is non-convex (concave) if it has interior angles greater than 180 degrees ? like stars or crescents.
Steps to Check Contour Convexity
You can use the following steps to check if a contour in an image is convex or not ?
1. Import the required library. In all the following Python examples, the required Python library is OpenCV.
2. Read the input image using cv2.imread() and convert it to grayscale.
3. Apply thresholding on the grayscale image to create a binary image.
4. Find the contours in the image using cv2.findContours() function.
5. Compute convexity using cv2.isContourConvex(cnt). It returns True if the contour is convex, else False.
6. Draw the contours on the input image and display the result.
Example 1: Checking Rectangle Convexity
In this example, we create a rectangle and check if its contour is convex ?
import cv2
import numpy as np
# Create a blank image and draw a white rectangle
img1 = np.zeros((350, 630, 3), dtype=np.uint8)
img1[100:250, 200:380, :] = 255
# Convert to grayscale
img = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# Apply threshold to get binary image
ret, thresh = cv2.threshold(img, 150, 255, 0)
# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours:", len(contours))
# Check convexity of the first contour
cnt = contours[0]
k = cv2.isContourConvex(cnt)
print("Convexity:", k)
# Get first point for text position
x, y = cnt[0][0]
# Draw contour and add text
cv2.drawContours(img1, [cnt], -1, (0, 255, 255), 3)
cv2.putText(img1, f'Convexity: {k}', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
print("Rectangle contour convexity result displayed")
Number of contours: 1 Convexity: True Rectangle contour convexity result displayed
Example 2: Checking Star Shape Convexity
In this example, we create a star shape and check if its contour is convex ?
import cv2
import numpy as np
# Create a blank image
img1 = np.zeros((400, 400, 3), dtype=np.uint8)
# Create a star shape using polygon points
center = (200, 200)
outer_radius = 100
inner_radius = 40
# Calculate star points (5-pointed star)
points = []
for i in range(10):
angle = i * np.pi / 5
if i % 2 == 0:
# Outer points
x = int(center[0] + outer_radius * np.cos(angle - np.pi/2))
y = int(center[1] + outer_radius * np.sin(angle - np.pi/2))
else:
# Inner points
x = int(center[0] + inner_radius * np.cos(angle - np.pi/2))
y = int(center[1] + inner_radius * np.sin(angle - np.pi/2))
points.append([x, y])
# Draw filled star
star_points = np.array(points, np.int32)
cv2.fillPoly(img1, [star_points], (255, 255, 255))
# Convert to grayscale
img = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
# Apply threshold
ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("Number of contours:", len(contours))
# Check convexity
cnt = contours[0]
k = cv2.isContourConvex(cnt)
print("Convexity:", k)
# Get first point for text position
x, y = cnt[0][0]
# Draw contour and add text
cv2.drawContours(img1, [cnt], -1, (0, 255, 255), 3)
cv2.putText(img1, f'Convexity: {k}', (x, y+30), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
print("Star shape convexity result displayed")
Number of contours: 1 Convexity: False Star shape convexity result displayed
Comparison of Convex vs Non-Convex Shapes
| Shape Type | Convex Result | Characteristics |
|---|---|---|
| Rectangle | True | All angles < 180°, no indentations |
| Circle | True | Perfectly curved, no indentations |
| Star | False | Has indentations, angles > 180° |
| Crescent | False | Concave shape with indentation |
Conclusion
Use cv2.isContourConvex() to determine if a contour represents a convex shape. Convex shapes like rectangles and circles return True, while concave shapes like stars return False. This is useful for shape classification and object recognition tasks.
