Image Segmentation: U-Net, Mask R-CNN & Segment Anything

1. What Is Image Segmentation?

Image segmentation is a computer vision task that divides an image into meaningful regions by assigning a label to individual pixels.

For example, in a medical image, segmentation can identify the exact boundaries of a tumor. In an autonomous driving system, it can distinguish roads, vehicles, pedestrians, buildings, and sidewalks.

Unlike image classification and object detection, segmentation provides pixel-level information.

Image Classification vs. Object Detection vs. Segmentation

TaskWhat it doesOutput
Image ClassificationIdentifies what an image containsClass label
Object DetectionLocates objects in an imageBounding boxes and labels
Semantic SegmentationAssigns a class to every pixelPixel-level class map
Instance SegmentationSeparates individual objects, even from the same classIndividual object masks
Panoptic SegmentationCombines semantic and instance segmentationUnified pixel-level representation

Types of Image Segmentation

1. Semantic Segmentation

Semantic segmentation assigns a class label to every pixel.

For example, all cars receive the same class label, regardless of how many cars appear in the image.

Applications:

  • Road and lane understanding
  • Medical image analysis
  • Satellite image classification
  • Agricultural monitoring

2. Instance Segmentation

Instance segmentation identifies individual objects separately.

For example, if an image contains five people, the model generates five separate masks.

Applications:

  • People counting
  • Autonomous vehicles
  • Retail analytics
  • Industrial inspection

3. Panoptic Segmentation

Panoptic segmentation combines semantic and instance segmentation.

It identifies individual objects, such as cars and people, while also classifying background regions such as roads, buildings, and sky.

2. How Image Segmentation Works

A typical image segmentation pipeline involves the following steps:

  1. Input image: Load an image from a dataset or camera.
  2. Preprocessing: Resize, normalize, and prepare the image.
  3. Feature extraction: Extract important visual features using a CNN or Transformer.
  4. Segmentation: Predict a class or object mask for each pixel.
  5. Post-processing: Apply thresholding, resizing, or mask refinement when necessary.
  6. Evaluation: Compare predicted masks with ground-truth masks.

The output is generally a segmentation mask with the same spatial dimensions as the input image.

Important Segmentation Concepts

Pixel Classification: Each pixel is assigned a class or object identity.

Mask: A binary or multi-class image representing the segmented region.

Encoder: Extracts increasingly meaningful visual features while reducing spatial dimensions.

Decoder: Reconstructs spatial information and generates the segmentation output.

Skip Connections: Transfer information from earlier network layers to later layers, helping preserve fine details.

3. U-Net: A Powerful Architecture for Semantic Segmentation

U-Net is a convolutional neural network architecture originally introduced for biomedical image segmentation in 2015.

It is particularly effective when training data is limited and precise object boundaries are important.

Its architecture resembles the letter U, which is why it is called U-Net.

<diagram-placeholder>U-Net Architecture: Encoder → Bottleneck → Decoder, with skip connections connecting corresponding encoder and decoder levels.</diagram-placeholder>

U-Net Architecture

U-Net consists of three major components:

1. Contracting Path (Encoder)

The encoder extracts features from the input image.

Typical operations include:

  • Convolution layers
  • ReLU activation
  • Max pooling
  • Feature map extraction

As the network moves deeper, spatial dimensions decrease while the number of feature channels generally increases.

2. Bottleneck

The bottleneck is the deepest part of the architecture.

It captures high-level semantic information about the image.

3. Expanding Path (Decoder)

The decoder reconstructs spatial information and generates the segmentation mask.

Typical operations include:

  • Transposed convolution or upsampling
  • Feature concatenation
  • Convolution layers
  • Pixel-level classification

Skip Connections in U-Net

One of U-Net's most important features is its skip connections.

They transfer feature maps from the encoder to corresponding decoder layers.

Why are they important?

During downsampling, some fine spatial details may be lost. Skip connections help recover these details by combining high-level semantic information with low-level spatial information.

This improves boundary detection and localization.

U-Net Loss Function

For binary segmentation, Binary Cross-Entropy (BCE) is commonly used.

\[ L_{BCE}=-\frac{1}{N}\sum_{i=1}^{N} [y_i\log(p_i)+(1-y_i)\log(1-p_i)] \]

Where:

  • \(N\) = Number of pixels
  • \(y_i\) = Actual pixel label
  • \(p_i\) = Predicted probability

Dice Loss is another popular choice, especially when the foreground occupies a small portion of the image.

\[ Dice=\frac{2|P\cap G|+\epsilon} {|P|+|G|+\epsilon} \]

\[ L_{Dice}=1-Dice \]

Where:

  • \(P\) = Predicted segmentation mask
  • \(G\) = Ground-truth mask
  • \(\epsilon\) = Small smoothing constant

A combined BCE and Dice loss can also be used.

U-Net Python Implementation

Install the required libraries:

pip install tensorflow matplotlib numpy

The following example demonstrates a simplified U-Net for binary image segmentation.

import tensorflow as tf
from tensorflow.keras import layers, Model

def conv_block(x, filters):
    x = layers.Conv2D(
        filters, 3, padding="same", activation="relu"
    )(x)

    x = layers.Conv2D(
        filters, 3, padding="same", activation="relu"
    )(x)

    return x


def build_unet(input_shape=(128, 128, 1)):

    inputs = layers.Input(input_shape)

    # Encoder
    c1 = conv_block(inputs, 32)
    p1 = layers.MaxPooling2D()(c1)

    c2 = conv_block(p1, 64)
    p2 = layers.MaxPooling2D()(c2)

    c3 = conv_block(p2, 128)
    p3 = layers.MaxPooling2D()(c3)

    # Bottleneck
    b = conv_block(p3, 256)

    # Decoder
    u3 = layers.Conv2DTranspose(
        128, 2, strides=2, padding="same"
    )(b)

    u3 = layers.Concatenate()([u3, c3])
    c4 = conv_block(u3, 128)

    u2 = layers.Conv2DTranspose(
        64, 2, strides=2, padding="same"
    )(c4)

    u2 = layers.Concatenate()([u2, c2])
    c5 = conv_block(u2, 64)

    u1 = layers.Conv2DTranspose(
        32, 2, strides=2, padding="same"
    )(c5)

    u1 = layers.Concatenate()([u1, c1])
    c6 = conv_block(u1, 32)

    # Binary segmentation output
    outputs = layers.Conv2D(
        1, 1, activation="sigmoid"
    )(c6)

    return Model(inputs, outputs)


model = build_unet()

model.compile(
    optimizer="adam",
    loss="binary_crossentropy",
    metrics=["accuracy"]
)

model.summary()

This code builds the model architecture but does not train it. To train the network, you need matching image and binary-mask pairs.

# X_train: input images
# y_train: corresponding binary masks

model.fit(
    X_train,
    y_train,
    epochs=20,
    batch_size=8,
    validation_data=(X_val, y_val)
)

Important: Prepare images and masks with compatible dimensions and normalize the image values. Binary masks should contain appropriate foreground and background labels. For imbalanced segmentation datasets, consider Dice Loss or a combined loss instead of relying only on pixel accuracy.

U-Net Applications

  • Medical imaging: Tumor and organ segmentation
  • Agriculture: Crop and plant disease analysis
  • Satellite imagery: Land-use segmentation
  • Industrial inspection: Defect identification
  • Biology: Cell and tissue segmentation

4. Mask R-CNN: Instance Segmentation

Mask R-CNN is an extension of Faster R-CNN designed to perform instance segmentation.

While object detection predicts bounding boxes and class labels, Mask R-CNN additionally generates a pixel-level mask for each detected object.

It was introduced in 2017 and became an influential architecture for instance segmentation.

Mask R-CNN Architecture

Mask R-CNN generally contains four important components:

1. Backbone Network

The backbone extracts visual features from an image.

Common examples include:

  • ResNet
  • ResNet with Feature Pyramid Network (FPN)

2. Region Proposal Network (RPN)

The RPN identifies potential object regions called region proposals.

It predicts:

  • Objectness scores
  • Candidate bounding boxes

3. RoIAlign

RoIAlign extracts fixed-size feature representations from proposed regions.

It avoids the spatial misalignment associated with the quantization used in earlier RoI Pooling approaches.

This is particularly important for generating accurate segmentation masks.

4. Prediction Heads

Mask R-CNN has separate prediction branches for:

  • Classification: Predicts the object category.
  • Bounding-box regression: Refines object coordinates.
  • Mask prediction: Generates a binary mask for each detected instance.

How Mask R-CNN Works

  1. The input image enters the backbone.
  2. The backbone extracts feature maps.
  3. RPN proposes possible object regions.
  4. RoIAlign extracts region-specific features.
  5. Classification predicts object categories.
  6. Bounding-box regression refines object locations.
  7. The mask branch generates an individual mask for each detected object.

Mask R-CNN Loss Function

Mask R-CNN combines multiple loss functions:

\[ L=L_{cls}+L_{box}+L_{mask} \]

Where:

  • \(L_{cls}\) = Classification loss
  • \(L_{box}\) = Bounding-box regression loss
  • \(L_{mask}\) = Mask prediction loss

Each component contributes to learning a different part of the segmentation task.

Mask R-CNN Python Implementation

Install the required libraries:

pip install torch torchvision pillow matplotlib

Example using a pretrained Mask R-CNN model from Torchvision:

import torch
import torchvision
from torchvision.transforms.functional import to_tensor
from PIL import Image
import matplotlib.pyplot as plt

# Load pretrained Mask R-CNN
weights = (
    torchvision.models.detection
    .MaskRCNN_ResNet50_FPN_Weights.DEFAULT
)

model = torchvision.models.detection.maskrcnn_resnet50_fpn(
    weights=weights
)

model.eval()

# Load image
image = Image.open("image.jpg").convert("RGB")

# Convert image to tensor
transform = weights.transforms()
image_tensor = transform(image)

# Run prediction
with torch.no_grad():
    prediction = model([image_tensor])[0]

# Display image
plt.figure(figsize=(10, 8))
plt.imshow(image)
plt.axis("off")

# Draw predicted masks
for i in range(len(prediction["scores"])):

    score = prediction["scores"][i].item()

    if score > 0.7:

        mask = prediction["masks"][i, 0].numpy()

        plt.imshow(
            mask,
            alpha=0.4,
            cmap="jet"
        )

plt.show()

The example uses pretrained weights and predicts instance masks for recognized objects. The confidence threshold is adjustable. A production visualization should also associate each mask with its predicted class and score.

Mask R-CNN Applications

  • Autonomous driving
  • Medical image analysis
  • Object counting
  • Robotics
  • Retail inventory analysis
  • Industrial quality inspection

5. Segment Anything Model (SAM)

Segment Anything Model (SAM) is a foundation model for image segmentation developed by Meta AI and introduced in 2023.

Traditional segmentation models are often trained for specific classes or datasets. SAM takes a more flexible approach by supporting prompt-based segmentation.

Users can provide prompts such as:

  • Points
  • Bounding boxes
  • Existing masks

SAM uses these prompts to generate segmentation masks.

What Makes SAM Different?

SAM is designed to segment a wide range of objects and regions without requiring a separate task-specific model for every category.

It was trained using the SA-1B dataset, which contains more than one billion masks across approximately 11 million images.

Its prompt-based design makes it useful for interactive annotation and general-purpose segmentation.

SAM Architecture

SAM consists of three major components:

1. Image Encoder

The image encoder processes the input image and generates image embeddings.

The original SAM uses a Vision Transformer-based image encoder.

2. Prompt Encoder

The prompt encoder converts user-provided prompts into embeddings.

Supported prompts include:

  • Foreground points
  • Background points
  • Bounding boxes
  • Mask inputs

3. Mask Decoder

The mask decoder combines image and prompt embeddings to generate segmentation masks.

It can produce multiple candidate masks and predicted quality scores.

<diagram-placeholder>SAM Architecture: Input Image → Image Encoder → Image Embeddings; User Prompt → Prompt Encoder; both feed into the Mask Decoder → Segmentation Masks.</diagram-placeholder>

How SAM Works

  1. Upload an image.
  2. SAM generates image embeddings.
  3. Provide a point, box, or mask prompt.
  4. The prompt encoder processes the prompt.
  5. The mask decoder combines the image and prompt information.
  6. SAM returns one or more candidate masks.

SAM Python Implementation

Install the original SAM dependencies:

pip install torch torchvision
pip install git+https://github.com/facebookresearch/segment-anything.git
pip install opencv-python matplotlib

Download a compatible pretrained SAM checkpoint from the official Segment Anything repository.

Example using a point prompt:

import cv2
import torch
import numpy as np
import matplotlib.pyplot as plt

from segment_anything import (
    sam_model_registry,
    SamPredictor
)

# Load SAM checkpoint
sam = sam_model_registry["vit_b"](
    checkpoint="sam_vit_b_01ec64.pth"
)

sam.to(
    device="cuda" if torch.cuda.is_available() else "cpu"
)

# Create predictor
predictor = SamPredictor(sam)

# Load image
image = cv2.imread("image.jpg")
image = cv2.cvtColor(
    image,
    cv2.COLOR_BGR2RGB
)

# Generate image embeddings
predictor.set_image(image)

# Point prompt: (x, y)
input_point = np.array([[300, 250]])

# 1 = foreground point
input_label = np.array([1])

# Generate masks
masks, scores, logits = predictor.predict(
    point_coords=input_point,
    point_labels=input_label,
    multimask_output=True
)

# Display results
plt.figure(figsize=(10, 8))
plt.imshow(image)

best_mask = masks[np.argmax(scores)]

plt.imshow(
    best_mask,
    alpha=0.5,
    cmap="jet"
)

plt.axis("off")
plt.show()

print("Mask scores:", scores)

The checkpoint must match the selected model type (vit_b in this example). The point coordinates must correspond to the original image dimensions.

SAM Applications

  • Interactive image annotation
  • Medical image research
  • Object extraction
  • Image editing workflows
  • Robotics
  • Dataset preparation
  • General-purpose segmentation

SAM Limitations

Although SAM is powerful, it has some limitations:

  • It may generate incorrect masks for unfamiliar or ambiguous objects.
  • It does not automatically provide semantic class labels for every mask.
  • Fine-grained boundaries can be challenging.
  • High-resolution image processing can require substantial memory and computation.
  • Domain-specific applications may still require specialized training or refinement.

6. U-Net vs. Mask R-CNN vs. SAM

All three architectures perform segmentation, but they solve different problems.

FeatureU-NetMask R-CNNSAM
Main taskSemantic segmentationInstance segmentationPrompt-based segmentation
ArchitectureEncoder-decoder CNNTwo-stage detection networkFoundation model with image and prompt encoders
InputImageImageImage and optional prompt
OutputPixel-class mapIndividual object masksPrompt-conditioned masks
Object separationNot inherently instance-awareYesDepends on prompts
TrainingUsually task-specificUsually task-specificPretrained general-purpose model
Best useMedical and domain-specific segmentationDetecting and separating objectsFlexible interactive segmentation

Which Model Should You Choose?

Choose U-Net when:

  • You need semantic segmentation.
  • You have a specialized dataset.
  • You are working with medical images.
  • You need a relatively compact model.

Choose Mask R-CNN when:

  • You need object detection and instance segmentation together.
  • Individual objects must be separated.
  • Bounding boxes and class labels are required.
  • You have annotated training data.

Choose SAM when:

  • You need flexible prompt-based segmentation.
  • You want to create masks quickly.
  • You are building interactive annotation tools.
  • You want a strong pretrained segmentation starting point.

7. Important Evaluation Metrics

Segmentation models require metrics that measure how accurately predicted masks overlap with ground-truth masks.

1. Intersection over Union (IoU)

IoU measures the overlap between the predicted mask and the actual mask.

\[ IoU=\frac{|P\cap G|}{|P\cup G|} \]

Where:

  • \(P\) = Predicted mask
  • \(G\) = Ground-truth mask

A higher IoU indicates better overlap.

2. Dice Coefficient

Dice measures the similarity between two segmentation masks.

\[ Dice=\frac{2|P\cap G|}{|P|+|G|} \]

Dice is particularly popular in medical image segmentation.

3. Pixel Accuracy

Pixel accuracy measures the proportion of correctly classified pixels.

\[ Pixel\ Accuracy= \frac{\text{Correctly Classified Pixels}} {\text{Total Pixels}} \]

However, pixel accuracy can be misleading when the background occupies most of an image.

4. Precision and Recall

\[ Precision=\frac{TP}{TP+FP} \]

\[ Recall=\frac{TP}{TP+FN} \]

Where:

  • TP = True Positive pixels
  • FP = False Positive pixels
  • FN = False Negative pixels

Precision measures how many predicted foreground pixels are correct. Recall measures how many actual foreground pixels are detected.

5. Mean IoU (mIoU)

Mean IoU calculates the average IoU across all classes.

\[ mIoU=\frac{1}{C}\sum_{i=1}^{C}IoU_i \]

Where \(C\) represents the number of classes.

For instance segmentation, Average Precision (AP) over different IoU thresholds is also widely used.

DatasetMain Purpose
COCOObject detection and instance segmentation
Pascal VOCObject recognition and segmentation
CityscapesUrban scene segmentation
ADE20KScene parsing and semantic segmentation
ISICSkin lesion segmentation
BraTSBrain tumor segmentation
DRIVERetinal blood vessel segmentation

Choose a dataset based on the segmentation task, annotation quality, image domain, and evaluation protocol.

9. Real-World Applications of Image Segmentation

Healthcare: Identifying tumors, organs, lesions, and anatomical structures.

Autonomous Vehicles: Separating roads, vehicles, pedestrians, traffic signs, and other objects.

Agriculture: Detecting crop regions, weeds, plant diseases, and fruits.

Satellite Imaging: Mapping buildings, forests, roads, water bodies, and land-use categories.

Manufacturing: Identifying surface defects, cracks, and damaged components.

Retail: Product segmentation, shelf analysis, and inventory monitoring.

Robotics: Understanding object boundaries and separating objects for manipulation.

10. Common Challenges in Image Segmentation

Class Imbalance

Some classes may occupy only a small number of pixels.

Solution: Use Dice Loss, focal loss, class weighting, or carefully designed sampling strategies.

Complex Object Boundaries

Objects may have irregular shapes or unclear boundaries.

Solution: Use high-resolution inputs, skip connections, boundary-aware losses, and suitable augmentation.

Limited Training Data

Segmentation requires pixel-level annotations, which can be expensive.

Solution: Use transfer learning, data augmentation, pretrained models, and interactive annotation tools.

Overlapping Objects

Objects may overlap or have similar visual features.

Solution: Use instance segmentation architectures such as Mask R-CNN or prompt-based approaches such as SAM.

Computational Cost

Large segmentation models can require significant GPU memory.

Solution: Use smaller backbones, image tiling, mixed-precision training, or optimized inference.

11. Best Practices for Building Segmentation Models

  1. Select the correct segmentation task before choosing an architecture.
  2. Use high-quality pixel-level annotations.
  3. Apply appropriate image and mask transformations.
  4. Ensure that geometric transformations are applied consistently to both images and masks.
  5. Use suitable loss functions for class imbalance.
  6. Evaluate with IoU, Dice, and class-wise metrics.
  7. Visualize predictions instead of relying only on numerical scores.
  8. Use pretrained models when appropriate.
  9. Test the model on images from different environments.
  10. Measure inference speed and memory consumption before deployment.

12. A Practical Learning Roadmap

If you are beginning with image segmentation, follow this progression:

Step 1: Learn the fundamentals

  • Image classification
  • Object detection
  • Semantic and instance segmentation
  • CNN architecture

Step 2: Implement U-Net

  • Build an encoder-decoder network.
  • Train it on a small segmentation dataset.
  • Evaluate using IoU and Dice.

Step 3: Explore Mask R-CNN

  • Understand region proposals.
  • Learn RoIAlign.
  • Generate individual object masks.

Step 4: Experiment with SAM

  • Load pretrained checkpoints.
  • Use point and box prompts.
  • Compare generated masks.

Step 5: Build a project Create a medical image segmentation tool, road segmentation application, or interactive object extraction system.

13. Frequently Asked Questions

Q1. What is image segmentation in deep learning?

Image segmentation is a computer vision task that assigns labels or object identities to individual pixels, allowing machines to understand the precise regions and boundaries within an image.

Q2. What is the difference between semantic and instance segmentation?

Semantic segmentation assigns the same class label to all pixels belonging to a category. Instance segmentation additionally separates individual objects belonging to that category.

Q3. Why is U-Net popular in medical imaging?

U-Net combines an encoder-decoder architecture with skip connections, helping preserve fine spatial details. It can also perform effectively with relatively limited annotated training data.

Q4. Is Mask R-CNN better than U-Net?

Neither is universally better. U-Net is commonly used for semantic segmentation, while Mask R-CNN is designed for instance segmentation with object detection.

Q5. What is Segment Anything Model (SAM)?

SAM is a promptable segmentation foundation model that generates masks based on prompts such as points, bounding boxes, or mask inputs.

Q6. Can SAM perform image classification?

SAM is designed for segmentation rather than conventional image classification. It can generate object masks but does not inherently assign a semantic category to every segmented region.

Q7. What is IoU in image segmentation?

Intersection over Union measures the overlap between predicted and ground-truth masks. A higher IoU indicates better segmentation overlap.

Q8. Which programming language is used for image segmentation?

Python is widely used because of its deep learning ecosystem, including TensorFlow, PyTorch, OpenCV, and segmentation libraries.

Q9. What is the difference between U-Net and SAM?

U-Net is typically trained for a particular segmentation task, whereas SAM is a pretrained promptable foundation model designed to segment a broad range of objects and regions.

Q10. What should beginners learn first?

Start with CNN fundamentals and semantic segmentation, then implement U-Net. After understanding the basics, move to Mask R-CNN and SAM.

Conclusion

Image segmentation enables computers to understand images at the pixel level and is essential in healthcare, autonomous driving, agriculture, robotics, and industrial automation.

U-Net provides an effective encoder-decoder architecture for semantic segmentation. Mask R-CNN combines object detection with instance-level mask prediction. Segment Anything introduces flexible prompt-based segmentation through a pretrained foundation model.

Understanding these three approaches provides a strong foundation for advanced computer vision and modern AI applications.

As the field evolves, segmentation models are becoming more flexible, accurate, and capable of working across different visual domains.