Learning/IVP/Session 08
Session 08🔍

Region Labeling & Edge Detection

Colorizing segmented regions and detecting edges with Prewitt gradient operators.


Learning Objectives

  • Map labeled regions to custom colors
  • Compute horizontal and vertical Prewitt gradients
  • Combine gradient components into edge magnitude
  • Threshold edges at multiple levels

Color Mapping by Region

After labeling, each region can be assigned a distinct color by creating a colormap indexed by label number. This makes it easy to visually inspect segmentation results.

Ex8_1 — Colorize labeled regionsPython
import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors

img = cv2.cvtColor(cv2.imread('objects.jpg'), cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

num_labels, labels = cv2.connectedComponents(binary)

# Create a colormap for N labels
cmap = plt.get_cmap('tab20', num_labels)
colored = cmap(labels / num_labels)   # RGBA float array
colored_uint8 = (colored[:, :, :3] * 255).astype(np.uint8)

Prewitt Operators

Prewitt operators compute image gradients in horizontal and vertical directions. The kernels approximate the first derivative. Gx detects vertical edges; Gy detects horizontal edges.

Ex8_2 — Prewitt edge detectionPython
import cv2
import numpy as np
from scipy.signal import convolve2d

img = cv2.imread('scene.jpg', cv2.IMREAD_GRAYSCALE).astype(np.float64)

# Prewitt kernels
Gx_kernel = np.array([[-1, 0, 1],
                       [-1, 0, 1],
                       [-1, 0, 1]], dtype=np.float64)

Gy_kernel = np.array([[-1,-1,-1],
                       [ 0, 0, 0],
                       [ 1, 1, 1]], dtype=np.float64)

Gx = convolve2d(img, Gx_kernel, mode='same', boundary='symm')
Gy = convolve2d(img, Gy_kernel, mode='same', boundary='symm')

# Gradient magnitude
G = np.sqrt(Gx**2 + Gy**2)

Edge Thresholding

After computing the gradient magnitude, apply different thresholds to control how many edges are visible. Higher threshold = only strong edges. Lower threshold = more edges including noise.

Ex8_2 — Threshold at multiple levelsPython
G_norm = (G / G.max() * 255).astype(np.uint8)

thresholds = [30, 60, 100]
results = []

for T in thresholds:
    _, edge_map = cv2.threshold(G_norm, T, 255, cv2.THRESH_BINARY)
    results.append(edge_map)