Superpixels - iffatAGheyas/computer-vision-handbook GitHub Wiki

✂️ Module 4: Focus on Superpixels

Superpixels are clusters of visually similar pixels that form a mid-level representation of an image. By grouping pixels based on colour, texture and proximity, superpixels reduce computational complexity while preserving important edges and structures. They’re commonly used as a preprocessing step in segmentation, object detection and other computer-vision tasks.


What Are Superpixels?

Superpixels are not individual pixels but clusters formed by grouping based on:

  • Colour
  • Texture
  • Proximity

They simplify the image by reducing the number of elements while maintaining edge and shape information.


Why Use Superpixels?

  • Preprocessing for object detection or segmentation
  • Speed: operate on fewer regions to accelerate processing
  • Edge preservation: maintain boundary details better than per-pixel methods

Popular Superpixel Algorithms

Algorithm Description OpenCV Support
SLIC Simple Linear Iterative Clustering
SEEDS Superpixels Extracted via Energy-Driven Sampling
LSC Linear Spectral Clustering

🐍 Python Code: Superpixels with SLIC

import cv2
import matplotlib.pyplot as plt

# Read image
img = cv2.imread("bird.jpg")

# Create SLIC superpixels
slic = cv2.ximgproc.createSuperpixelSLIC(
    img,
    algorithm=cv2.ximgproc.SLICO,
    region_size=30,
    ruler=10.0
)
slic.iterate(10)

# Obtain boundary mask and highlight in red
mask = slic.getLabelContourMask()
img[mask == 255] = (0, 0, 255)

# Display result
plt.figure(figsize=(6, 6))
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.axis("off")
plt.show()

image

🖼️ Superpixel Output Explanation

After running the SLIC superpixel code, you’ll see your original image overlaid with red polygonal boundaries. Here’s what you’re looking at:

  1. Superpixel Regions
    Each contiguous region enclosed by red lines is a superpixel—a cluster of neighbouring pixels that share similar colour and texture. Instead of processing millions of individual pixels, algorithms can operate on these ~thirty-pixel patches.

  2. Red Contours
    The red mask is generated by:

   mask = slic.getLabelContourMask()
   img[mask == 255] = (0, 0, 255)

Wherever mask == 255, we draw a red boundary, highlighting the borders between adjacent superpixels.

Parameters at Work

  • region_size = 30
    Aims for superpixels of roughly 30×30 pixels, balancing detail and computational load.

  • ruler = 10.0
    Controls the trade-off between colour similarity (group pixels by hue/intensity) and spatial proximity (keep them compact). A larger ruler value pulls regions into tighter, more regular shapes; a smaller value sticks closely to colour variations.