Detecting shapes like circles, rectangles, and polygons is an important task
in computer vision. OpenCV provides powerful tools such as cv2.findContours(),
cv2.approxPolyDP(), and cv2.HoughCircles() to identify and draw different shapes.
Using contours and cv2.approxPolyDP(), we can approximate the number of sides
and classify the shape (triangle, rectangle, polygon).
import cv2
img = cv2.imread("shapes.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt, True), True)
if len(approx) == 3:
shape = "Triangle"
elif len(approx) == 4:
shape = "Rectangle"
elif len(approx) > 4:
shape = "Polygon"
else:
shape = "Unknown"
cv2.drawContours(img, [approx], 0, (0,255,0), 2)
x, y = approx.ravel()[0], approx.ravel()[1] - 10
cv2.putText(img, shape, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
cv2.imshow("Shape Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Circles can be detected using the Hough Circle Transform method with cv2.HoughCircles().
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1.2, minDist=50,
param1=100, param2=30, minRadius=20, maxRadius=100)
if circles is not None:
circles = circles[0, :]
for (x, y, r) in circles:
cv2.circle(img, (x, y), r, (255, 0, 0), 2)
cv2.putText(img, "Circle", (x-10, y-10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
cv2.imshow("Circle Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned how to detect rectangles, polygons, and circles in OpenCV.
These techniques are widely used in object recognition, robotics, document analysis, and pattern detection.
👉 Next, we will explore color detection and masking in OpenCV.
