Skip to main content
Semantic segmentation assigns a class label to every pixel in an image, enabling detailed scene understanding. OpenCV’s DNN module supports various segmentation architectures trained on datasets like PASCAL VOC, Cityscapes, and COCO.

Supported Models

  • FCN (Fully Convolutional Networks) - FCN-8s, FCN-ResNet101
  • ENet - Efficient neural network for real-time segmentation
  • DeepLab - State-of-the-art segmentation with atrous convolution
  • U-Net - Popular architecture for medical image segmentation
  • PSPNet - Pyramid Scene Parsing Network

Python Implementation

1

Import Libraries

2

Load the Model

3

Generate or Load Colors

4

Prepare Input Image

Different segmentation models require different input sizes:
  • ENet: 512x256
  • FCN-8s: 500x500
  • FCN-ResNet101: 500x500
5

Run Inference

6

Post-process Segmentation Map

7

Overlay and Display

C++ Implementation

Creating a Legend

Display a legend showing class names and colors:
C++ version:

Model Configurations

ENet (Torch)

Download: https://github.com/e-lab/ENet-training Classes: 20 road scene classes (Cityscapes-style)

FCN-8s (Caffe)

Download: http://dl.caffe.berkeleyvision.org/fcn8s-heavy-pascal.caffemodel Classes: 21 PASCAL VOC classes

FCN-ResNet101 (ONNX)

Download: https://github.com/onnx/models (ONNX Model Zoo)

Common Segmentation Classes

Road scene segmentation with 20 classes:
  • road
  • sidewalk
  • building
  • wall
  • fence
  • pole
  • traffic light
  • traffic sign
  • vegetation
  • terrain
  • sky
  • person
  • rider
  • car
  • truck
  • bus
  • train
  • motorcycle
  • bicycle

Performance Optimization

1

Use GPU Acceleration

2

Reduce Input Size

Smaller input sizes process faster but may lose detail:
3

Use Efficient Models

Choose models based on speed/accuracy tradeoff:
  • ENet: Real-time, good for road scenes
  • FCN-8s: Moderate speed, high accuracy
  • DeepLab: Best accuracy, slower

Blending Segmentation with Original Image

Adjust the blend ratio for different visualization effects:

Complete Example with Video

Semantic segmentation is computationally expensive. For real-time applications on CPU, use lightweight models like ENet or reduce input resolution.

Source Code

Complete source code for semantic segmentation:
  • Python: samples/dnn/segmentation.py
  • C++: samples/dnn/segmentation.cpp