A Python implementation of graph-based image segmentation using the SLIC (Simple Linear Iterative Clustering) superpixel algorithm via OpenCV, partitioning images into perceptually meaningful regions based on colour and spatial similarity.
Graph-based image segmentation treats an image as a weighted graph where each pixel is a node and edge weights represent the dissimilarity between neighbouring pixels. The SLIC algorithm clusters pixels into compact superpixels by iteratively minimising a combined colour and spatial distance metric in the CIELAB colour space. Each resulting segment is rendered with a distinct random colour to visualise the partition.
This approach enables robust segmentation across images with diverse intensity distributions, complex textures, and irregular object boundaries.
Input Image (RGB)
│
▼
Grayscale Conversion
│
▼
SLIC Superpixel Segmentation
region_size = k
ruler = 10.0 (spatial regularisation)
│
▼
Segment Label Extraction
│
▼
Random Colour Assignment per Segment
│
▼
Contour Detection per Segment Mask
(cv2.RETR_EXTERNAL + cv2.CHAIN_APPROX_SIMPLE)
│
▼
Region Filling with Assigned Colours
│
▼
Segmented Output Image
| Parameter | Default | Description |
|---|---|---|
k (region_size) |
100 | Target superpixel size in pixels — larger values produce fewer, coarser segments |
ruler |
10.0 | Spatial regularisation weight — higher values enforce more uniform superpixel shapes |
min_size |
50 | Minimum superpixel size — segments below this threshold are merged with neighbours |
sigma |
0.5 | Gaussian smoothing applied before segmentation — higher values smooth boundaries |
Input: High-contrast RGB image with complex foreground and textured background Output: Colour-coded segmentation map separating regions by colour and texture similarity
The SLIC algorithm successfully partitions the image into spatially compact, perceptually uniform superpixels, clearly delineating foreground objects from background regions.
graph-image-segmentation-slic/
├── graph_image_segmentation.py # Segmentation pipeline
└── README.md
opencv-python>=4.5.0
opencv-contrib-python>=4.5.0
numpy
Install dependencies:
pip install opencv-python opencv-contrib-python numpy
opencv-contrib-pythonis required forcv2.ximgproc.createSuperpixelSLIC.
- Place your input image in the project directory
- Update the
image_pathvariable ingraph_image_segmentation.py - Run:
python graph_image_segmentation.pyTwo windows will open displaying the original image and the segmented output. Press any key to close.
- Achanta, R. et al. (2012). SLIC Superpixels Compared to State-of-the-Art Superpixel Methods. IEEE Transactions on Pattern Analysis and Machine Intelligence, 34(11), 2274–2282.
- Felzenszwalb, P. & Huttenlocher, D. (2004). Efficient Graph-Based Image Segmentation. International Journal of Computer Vision, 59(2), 167–181.
Computer Vision — M.Eng. Information Technology SRH Hochschule Heidelberg, Germany Supervised by Prof. Dr. Milan Gnjatovic