Contours - iffatAGheyas/computer-vision-handbook GitHub Wiki

📐 Contours & Connected Components

Understanding how to extract and analyse regions and boundaries in binary (or segmented) images.


1. Connected Components

A connected component is a set of adjacent pixels sharing the same value (typically in a binary image)—used to detect and label distinct blobs or objects.

Think: “How many isolated white blobs are there in this image?”

Code: Connected Components with OpenCV

import cv2
import numpy as np
import matplotlib.pyplot as plt

# 1. Read and binarise the image
img_gray = cv2.imread("bird.jpg", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

# 2. Extract connected components
num_labels, labels_img = cv2.connectedComponents(binary)

# 3. Colour each label uniquely
label_hue = np.uint8(179 * labels_img / np.max(labels_img))
blank_ch  = 255 * np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2RGB)

# 4. Display result
plt.figure(figsize=(6, 6))
plt.imshow(labeled_img)
plt.title(f"{num_labels - 1} Connected Components Found")
plt.axis("off")
plt.show()

image

Output:

  • num_labels: total components (including background)
  • labels_img: image where each pixel is marked with its component ID

2. Contours — The Outlines of Shapes

Contours are curves joining all continuous points along the boundary of shapes in a binary image. They serve as the “skeleton” of object outlines.

Use Cases

  • Shape analysis
  • Object detection and counting
  • Measuring area, perimeter, aspect ratio

Code: Finding & Drawing Contours

import cv2
import matplotlib.pyplot as plt

# 1. Binarise the image
_, binary = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

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

# 3. Draw contours on a colour image
img_contours = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)
cv2.drawContours(img_contours, contours, -1, (0, 255, 0), 2)

# 4. Display result
img_rgb = cv2.cvtColor(img_contours, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(6, 6))
plt.imshow(img_rgb)
plt.title(f"{len(contours)} Contours Found")
plt.axis("off")
plt.show()

image

Output:

  • num_labels: total components (including background)
  • labels_img: image where each pixel is marked with its component ID

Key Parameters in cv2.findContours

Parameter Meaning
cv2.RETR_EXTERNAL Retrieve only outermost contours
cv2.RETR_TREE Retrieve all contours + hierarchy info
cv2.CHAIN_APPROX_SIMPLE Compress horizontal/vertical segments

Summary

Tool Purpose Function
Connected Components Label isolated regions cv2.connectedComponents()
Contours Find shape outlines cv2.findContours()
Draw Contours Visualise contours on image cv2.drawContours()