Image segmentation labels every pixel of an image. Instead of a box around a tumour, a road or a leaf, you get its exact shape – essential in medical imaging, agriculture, satellite mapping and autonomous driving.
What You Will Learn
- Semantic, instance and panoptic segmentation
- Classic segmentation with thresholding
- IoU and Dice for masks (tested)
- U-Net architecture
- YOLO segmentation and Segment Anything (SAM)
Prerequisites
Types of Segmentation
| Type | Question | Example output |
|---|---|---|
| Semantic | Which class is each pixel? | All “person” pixels share one label |
| Instance | Which object is each pixel? | Person 1, person 2, person 3 separately |
| Panoptic | Both | Every object instance + background classes (road, sky) |
Classic Segmentation
For simple, high-contrast images, thresholding and contours already segment objects. Other classic tools: watershed for touching objects, k-means on pixel colours, GrabCut for foreground extraction.
Measuring Mask Quality
import numpy as np
gt = np.zeros((10, 10), int); gt[2:8, 2:8] = 1 # true mask: 6x6 square
pred = np.zeros((10, 10), int); pred[3:9, 3:9] = 1 # prediction shifted by 1 pixel
inter = (gt & pred).sum()
union = (gt | pred).sum()
print(inter, union, round(inter / union, 3),
round(2 * inter / (gt.sum() + pred.sum()), 3), # Dice
round((gt == pred).mean(), 2)) # pixel accuracy
25 47 0.532 0.694 0.78
Explanation: A one-pixel shift gives IoU 0.53 and Dice 0.69, while pixel accuracy still says 78% – inflated by the easy background pixels. Use IoU (Jaccard) or Dice for segmentation, especially when objects are small; Dice is popular in medical imaging.
U-Net
U-Net is the classic segmentation network: an encoder shrinks the image to capture “what”, a decoder upsamples back to full size to recover “where”, and skip connections copy fine details from encoder to decoder. It works well even with a few hundred labelled images and is the standard in medical imaging.
# pip install segmentation-models-pytorch
import segmentation_models_pytorch as smp
model = smp.Unet(encoder_name="resnet34", encoder_weights="imagenet",
in_channels=3, classes=1) # binary mask; train with Dice + BCE loss
loss = smp.losses.DiceLoss(mode="binary")
YOLO Segmentation
from ultralytics import YOLO
model = YOLO("yolo26n-seg.pt") # instance segmentation model
res = model("farm.jpg")[0]
print(len(res.masks.data), "objects") # one mask per detected object
res.save("farm_masks.jpg")
Segment Anything (SAM)
Meta’s Segment Anything models segment almost any object from a prompt – a click, a box or (in newer versions) text – without task-specific training. They are excellent for speeding up labelling and for zero-shot segmentation; fine-tuned task models are usually still better for one specific production task.
from ultralytics import SAM
sam = SAM("sam2.1_b.pt")
res = sam("leaf.jpg", points=[[320, 240]], labels=[1]) # one positive click
Applications
- Medical: tumours, organs, cells
- Agriculture: leaf disease area, weed detection
- Satellite: buildings, roads, water bodies
- Retail and manufacturing: defect areas
- Photo editing: background removal
Series
Computer vision series: OpenCV Intro · Image Processing · Image Classification · Data Augmentation · CNN · Transfer Learning · Object Detection (YOLO) · Image Segmentation · OCR · Face Detection
Interview Questions
Q: Semantic vs instance segmentation?
Semantic labels pixel classes; instance also separates individual objects of the same class.
Q: Why not use pixel accuracy?
Background dominates, so a poor mask can still score high; IoU and Dice focus on the object.
Q: What are skip connections in U-Net?
Links copying encoder feature maps to the decoder to preserve spatial detail.
Practice Exercises
- Compute IoU and Dice when the prediction is shifted by 2 pixels.
- Run YOLO segmentation on a photo and compute each object’s area in pixels.
Summary
Segmentation labels every pixel. Evaluate with IoU and Dice, use U-Net for small specialised datasets, YOLO-seg for real-time instances and SAM for prompt-based, zero-shot masks.
Next: OCR in Python
Machine Learning Tutorials, Courses and Certifications