Overlay an image segmentation with Numpy and Matplotlib

Image segmentation overlay is a technique to visualize segmented regions on top of the original image. Using NumPy and Matplotlib, we can create masks and overlay them with transparency to highlight specific areas of interest.

Steps to Overlay Image Segmentation

  • Create a binary mask array to define the segmented region

  • Generate or load the base image data

  • Use np.ma.masked_where() to create a masked array

  • Display the original image and overlay using imshow()

  • Apply transparency with the alpha parameter for better visualization

Example

Here's how to create an image segmentation overlay ?

import matplotlib.pyplot as plt
import numpy as np

# Set figure parameters
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create a binary mask (10x10 array)
mask = np.zeros((10, 10))
mask[3:-3, 3:-3] = 1  # Set center region to 1

# Create base image with some noise
im = mask + np.random.randn(10, 10) * 0.01

# Create masked array for overlay
masked = np.ma.masked_where(mask == 0, mask)

# Create subplots
plt.figure()

# Display original image
plt.subplot(1, 2, 1)
plt.imshow(im, 'gray', interpolation='none')
plt.title('Original Image')

# Display image with segmentation overlay
plt.subplot(1, 2, 2)
plt.imshow(im, 'gray', interpolation='none')
plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)
plt.title('With Segmentation Overlay')

plt.show()

How It Works

The np.ma.masked_where() function creates a masked array where values meeting the condition (mask == 0) are hidden. The alpha=0.7 parameter makes the overlay semi-transparent, allowing the underlying image to show through.

Key Parameters

Parameter Purpose Example Value
alpha Controls transparency 0.7 (70% opacity)
interpolation Pixel rendering method 'none' for sharp edges
colormap Color scheme for overlay 'jet', 'hot', 'viridis'

Conclusion

Image segmentation overlay combines np.ma.masked_where() with Matplotlib's transparency features. This technique is essential for visualizing computer vision results and highlighting regions of interest in images.

Updated on: 2026-03-25T20:05:53+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements