A Beginner’s Guide to Scipy.ndimage


Scipy.ndimage is a package in the Scipy library that is used to perform image processing tasks. It provides functions to perform operations like filtering, interpolation, and morphological operations on images. In this guide, we will cover the basics of Scipy.ndimage and how to use it to manipulate images.

What is Scipy.ndimage?

Scipy.ndimage is a subpackage of the SciPy library that provides multi-dimensional image processing functions. It is mainly used for image filtering, measurements, and morphology. Scipy.ndimage can be used for tasks such as smoothing, sharpening, edge detection, and noise reduction in images.

One of the major benefits of using Scipy.ndimage is that it provides a collection of fast and efficient image processing routines that have been optimized to work on large datasets. These routines can be used to process images with millions of pixels in a matter of seconds.

Scipy.ndimage also provides a range of filters such as Gaussian filters, median filters, and Sobel filters that can be applied to images to achieve different effects. For instance, Gaussian filters are often used for smoothing an image while preserving the edges, while Sobel filters are used for edge detection.

In addition to these basic functions, Scipy.ndimage also provides advanced functions such as label identification and watershed segmentation. These functions are useful for identifying objects within an image and segmenting them into separate regions.

Overall, Scipy.ndimage is a powerful tool for anyone working with digital images. Whether you are working with medical images or satellite imagery, Scipy.ndimage can help you process your data quickly and efficiently.


Scipy.ndimage is a module of the Scipy library that provides a collection of functions for image processing. Before using Scipy.ndimage, you need to install the Scipy library. If you have not installed Scipy yet, you can install it using pip. Open your command prompt or terminal and type the following command:

pip install scipy

Once you have installed Scipy, you can import the ndimage module using the following command:

from scipy import ndimage

This will allow you to use all the functions provided by the Scipy.ndimage module.

Image I/O

Scipy.ndimage is a powerful library for image processing and analysis in Python. One of the most important aspects of image processing is the ability to read, write and manipulate images. Scipy.ndimage provides a variety of functions for handling different image formats and loading them into memory.

To read an image using Scipy.ndimage, we can use the `imread()` function. This function takes the path to the image file as its argument and returns a NumPy array containing the pixel values of the image.

from scipy import ndimage
import matplotlib.pyplot as plt

# Read an image using imread()
image = ndimage.imread('path/to/image.png')

# Display the image using imshow()

Similarly, to save an image to disk, we can use the `imsave()` function. This function takes two arguments: the path to save the file and the NumPy array containing the pixel values.

# Save an image using imsave()
ndimage.imsave('path/to/new_image.png', image)

In addition, Scipy.ndimage also provides functions for converting images between different color spaces such as RGB, grayscale, HSV etc. These functions can be used to preprocess images before applying filters or other operations.

# Convert an RGB image to grayscale
gray_image = ndimage.imread('path/to/image.png', mode='L')

Overall, Scipy.ndimage provides a comprehensive set of tools for handling images in Python, making it an essential library for any beginner looking to get started with image processing.

Image Filtering

Image filtering is an important concept in image processing. It involves the modification of an image’s pixel values based on a certain mathematical operation. This can be useful in removing noise, highlighting certain features or edges, and smoothing the image.

The Scipy.ndimage library provides various functions for image filtering. One such function is the “convolve” function. This function applies a convolution operation to the input image using a given kernel. The kernel is a small matrix that specifies how to combine neighboring pixels in the input image to obtain the output pixel value.

Here’s an example of how to apply a 3×3 median filter to an image using Scipy.ndimage:

import numpy as np
from scipy import ndimage

# Load the image
img = ndimage.imread('example_image.png', flatten=True)

# Apply median filter
img_median = ndimage.median_filter(img, size=3)

# Display the filtered image
import matplotlib.pyplot as plt
plt.imshow(img_median, cmap='gray')

In this example, we first load an example image and then apply a median filter with a kernel size of 3×3 using the “median_filter” function. Finally, we display the filtered image using Matplotlib.

Other types of filters that can be applied using Scipy.ndimage include Gaussian filters, maximum and minimum filters, and Sobel filters for edge detection. By experimenting with different types of filters and kernel sizes, you can achieve various effects on your images.

Morphological Operations

Scipy.ndimage is a powerful Python library used for image processing and analysis. One of the most useful features of this library is its ability to perform morphological operations on images.

Morphological operations involve the manipulation of shapes in an image. These operations are useful for tasks such as noise removal, edge detection, and object segmentation. Scipy.ndimage provides several functions for performing morphological operations on images.

One common morphological operation is erosion, which involves shrinking the boundaries of an object in an image. This can be useful for removing small objects or filling in gaps between larger objects. The


function can be used to perform erosion on a binary image.

Another common morphological operation is dilation, which involves expanding the boundaries of an object in an image. This can be useful for filling in small gaps or connecting nearby objects. The


function can be used to perform dilation on a binary image.

Opening and closing are two additional morphological operations that involve combining erosion and dilation. Opening involves performing erosion followed by dilation, while closing involves performing dilation followed by erosion. These operations can be useful for smoothing out the boundaries of objects or separating overlapping objects.

In summary, morphological operations are a powerful tool for manipulating shapes in an image using Scipy.ndimage. By understanding these concepts and utilizing the appropriate functions, you can achieve impressive results in your image processing tasks.

Distance Transform

Scipy.ndimage is a powerful library in Python for image processing and manipulation. One of the functions provided by this library is the distance transform.

The distance transform calculates the distance of each pixel to the nearest pixel that belongs to a specified background. This can be useful in various image processing tasks, such as object recognition or edge detection.

To use the distance transform function in Scipy.ndimage, we first need to import it:

from scipy import ndimage

Next, we can load an image using any of the methods available in Python, such as the Pillow library:

from PIL import Image

image = Image.open("example_image.png")

We can then convert the image to a NumPy array and apply the distance transform:

import numpy as np

array = np.array(image)

distance = ndimage.distance_transform_edt(array)

In this example, we used the `distance_transform_edt` function to calculate the Euclidean distance transform. Other options include `distance_transform_cdt` for calculating the chessboard distance transform, or `distance_transform_bf` for a brute-force approach.

The resulting `distance` array contains the distances of each pixel to the nearest background pixel. We can visualize this by plotting it using Matplotlib:

import matplotlib.pyplot as plt


This will display an image where brighter pixels represent areas that are closer to the background.

Overall, the distance transform is a powerful tool for various image processing tasks, and Scipy.ndimage provides an easy-to-use implementation of it in Python.

Object Measurements

Scipy.ndimage provides a set of functions for measuring different properties of objects in an image. These measurements can be used to extract useful information from an image, such as the size and shape of objects, the location of different features, and the intensity or color of pixels.

One commonly used function for object measurements is `label`, which assigns a unique integer label to each connected component in an image. This allows us to identify and separate individual objects in an image, even if they are touching or overlapping.

Once we have labeled the objects in an image, we can use other functions to measure their properties. For example, `sum` computes the sum of pixel values within each labeled object, while `mean` computes the mean pixel value. Other functions like `maximum`, `minimum`, and `standard_deviation` can be used to compute other statistical properties.

We can also measure geometric properties of objects, such as their area, perimeter, and bounding box. The `measurements.regionprops` function provides a convenient way to compute these properties for all labeled objects in an image at once.

Here is an example that demonstrates how to use some of these functions:

import numpy as np
from scipy import ndimage

# Create a binary image with two connected components
image = np.zeros((10, 10), dtype=np.int)
image[1:4, 1:4] = 1
image[6:9, 6:9] = 2

# Label the connected components
labeled_image, num_features = ndimage.label(image)

# Measure the total area and mean intensity of each component
areas = ndimage.sum(image, labeled_image, range(1, num_features+1))
intensities = ndimage.mean(image, labeled_image, range(1, num_features+1))

# Print the results
for i in range(num_features):
    print(f"Object {i+1}: area={areas[i]}, intensity={intensities[i]}")

This code creates a 10×10 binary image with two connected components labeled as 1 and 2, respectively. It then uses `ndimage.label` to label the components, and `ndimage.sum` and `ndimage.mean` to compute the area and mean intensity of each component. Finally, it prints the results for each component.


In conclusion, Scipy.ndimage is a powerful library for image processing in Python. It provides a wide range of functions for operations such as filtering, segmentation, and morphology. With its easy-to-use interface and extensive documentation, even beginners can quickly get up to speed with the library.

Some of the key takeaways from this guide include:

  • – Scipy.ndimage is a sub-library of Scipy that specializes in image processing.
  • – It provides functions for filtering, segmentation, morphology, and more.
  • – The library works with both 2D and 3D images.
  • – Operations can be performed on individual pixels or entire images.
  • – The library is designed to work with NumPy arrays.
  • – Various interpolation methods are available for resampling images.
  • – The library also includes functions for feature detection and measurement.

Overall, Scipy.ndimage is an essential tool for anyone working with image data in Python. Whether you’re analyzing medical images, satellite imagery, or anything in between, this library has everything you need to get the job done efficiently and effectively.
Interested in learning more? Check out our Introduction to Python course!

How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!

Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]