Contours
Contours are the continuous curves that follow the boundaries of objects in a binary image. They are used to find, measure, and describe object shapes.
10 min•By Priygop Team•Updated 2026
Finding and Drawing Contours
Finding and Drawing Contours
import cv2
import numpy as np
image = cv2.imread("photo.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Find contours
# RETR_EXTERNAL: only outermost contours (ignores holes)
# CHAIN_APPROX_SIMPLE: compress straight lines to save memory
contours, hierarchy = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print(f"Found {len(contours)} contours")
# Draw all contours on a copy
result = image.copy()
cv2.drawContours(result, contours, -1, (0, 255, 0), 2) # -1 = draw all
# Analyse each contour
for i, contour in enumerate(contours):
area = cv2.contourArea(contour)
perimeter = cv2.arcLength(contour, closed=True)
x, y, w, h = cv2.boundingRect(contour)
if area > 500: # Ignore tiny contours
print(f"Contour {i}: area={area:.0f}, perimeter={perimeter:.0f}, bbox={w}x{h}")
cv2.rectangle(result, (x, y), (x+w, y+h), (255, 0, 0), 1)
cv2.imwrite("contours.jpg", result)Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment