Recently, I was working on an image analysis project where I needed to read and manipulate images using Python. This is when I discovered the power of SciPy’s ndimage module and its imread function.
The ndimage module offers a comprehensive suite of image processing tools, with imread being particularly useful for reading images as NumPy arrays. This makes it perfect for various image analysis and manipulation tasks.
In this article, I’ll share practical ways to use the imread function in SciPy’s ndimage module, along with some alternatives since this function has been deprecated in newer versions.
What is Ndimage Imread?
The imread function in SciPy’s ndimage module was designed to read an image file and convert it into a NumPy array. This conversion is essential as it allows us to perform mathematical operations and apply various algorithms to the image data.
Here’s a basic example of how it worked:
from scipy.ndimage import imread
# Read an image into a NumPy array
img_array = imread('sample_image.jpg')
# Check the shape of the array
print(img_array.shape)Imread Deprecation, What You Need to Know
It’s important to note that the imread function has been deprecated in SciPy since version 1.0.0 and was completely removed in version 1.2.0. This means if you’re using a recent version of SciPy, you’ll need to use alternatives.
The deprecation was done to reduce duplication of functionality across different libraries and encourage the use of more specialized image processing libraries.
Alternatives to SciPy Ndimage Imread
Now, I will explain some alternatives to SciPy Ndimage Imread.
Method 1: Use Matplotlib’s imread
Matplotlib provides a simple and effective alternative to SciPy’s imread:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Read image
img = mpimg.imread('usa_landmark.jpg')
# Display the image
plt.imshow(img)
plt.axis('off') # Hide axes
plt.show()
# Print shape to understand dimensions
print(f"Image shape: {img.shape}")I executed the above example code and added the screenshot below.

This approach is perfect for simple image reading tasks, especially when you plan to visualize the image using Matplotlib anyway.
Read Python SciPy Pairwise Distance
Method 2: Use Imageio
Imageio is a powerful library specifically designed for image I/O:
import imageio
import numpy as np
# Read image
img = imageio.imread('new_york_skyline.jpg')
# Convert to grayscale if needed
if len(img.shape) == 3: # Color image
gray_img = np.mean(img, axis=2).astype(np.uint8)
print(f"Converted from {img.shape} to {gray_img.shape}")I executed the above example code and added the screenshot below.

Imageio is particularly useful because it handles a wide variety of image formats and provides additional functionality for working with image metadata.
Check out Python SciPy Spatial Distance Cdist
Method 3: Use PIL/Pillow
Pillow (PIL) is one of the most comprehensive image processing libraries for Python:
from PIL import Image
import numpy as np
# Open image
pil_img = Image.open('grand_canyon.jpg')
# Convert to array
img_array = np.array(pil_img)
# Show image info
print(f"Format: {pil_img.format}")
print(f"Mode: {pil_img.mode}")
print(f"Dimensions: {pil_img.size}")
print(f"Array shape: {img_array.shape}")I executed the above example code and added the screenshot below.

Pillow offers extensive functionality for image manipulation, making it ideal for more complex image processing tasks.
Method 4: Use OpenCV
OpenCV is the powerhouse of computer vision libraries:
import cv2
import numpy as np
# Read image (BGR format by default)
img = cv2.imread('statue_of_liberty.jpg')
# Convert BGR to RGB if needed
rgb_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Apply a simple filter
blurred = cv2.GaussianBlur(img, (5, 5), 0)OpenCV is my go-to choice for advanced image processing and computer vision tasks. It’s incredibly powerful but might be overkill for simple image reading needs.
Advanced Usage Patterns
Let me explain to you the advanced usage pattern.
Reading and Flattening Images
Sometimes you need to convert an image to grayscale or flatten its dimensions:
import imageio
import numpy as np
# Read image
img = imageio.imread('golden_gate.jpg')
# Method 1: Convert color image to grayscale
if len(img.shape) == 3:
gray_img = np.mean(img, axis=2).astype(np.uint8)
# Method 2: Flatten completely (for machine learning)
flattened = img.flatten()
print(f"Original shape: {img.shape}, Flattened: {flattened.shape}")This flattening technique is particularly useful when preparing image data for machine learning algorithms that expect 1D input features.
Batch Processing Multiple Images
For data science projects, you often need to process multiple images:
import os
import numpy as np
from PIL import Image
def load_image_dataset(directory, size=(64, 64)):
images = []
filenames = []
for filename in os.listdir(directory):
if filename.endswith(('.jpg', '.jpeg', '.png')):
# Full path
file_path = os.path.join(directory, filename)
# Open and resize image
img = Image.open(file_path).resize(size)
# Convert to array and normalize
img_array = np.array(img) / 255.0
images.append(img_array)
filenames.append(filename)
return np.array(images), filenames
# Example usage
images, names = load_image_dataset('us_landmarks')
print(f"Loaded {len(images)} images with shape {images[0].shape}")This function is invaluable when working with image datasets for machine learning projects.
Read Python SciPy Optimize Root
Practical Applications
Now, I will show you the practical applications of SciPy’s Ndimage Imread.
Image Feature Extraction
import numpy as np
from PIL import Image
from scipy import ndimage
def extract_image_features(image_path):
# Load image
img = np.array(Image.open(image_path).convert('L')) # Convert to grayscale
# Basic features
mean_val = np.mean(img)
std_val = np.std(img)
# Edge detection using Sobel filter
sobel_x = ndimage.sobel(img, axis=0)
sobel_y = ndimage.sobel(img, axis=1)
edge_magnitude = np.hypot(sobel_x, sobel_y)
edge_mean = np.mean(edge_magnitude)
return {
'mean_intensity': mean_val,
'std_intensity': std_val,
'edge_strength': edge_mean
}
# Example
features = extract_image_features('washington_dc.jpg')
print(features)This example demonstrates how to extract meaningful features from images for classification or analysis.
Image Preprocessing for Machine Learning
import numpy as np
from PIL import Image
def preprocess_for_ml(image_path, target_size=(224, 224)):
# Open and resize
img = Image.open(image_path).resize(target_size)
# Convert to array and normalize
img_array = np.array(img) / 255.0
# Handle grayscale images
if len(img_array.shape) == 2:
img_array = np.stack((img_array,) * 3, axis=-1)
# Ensure we have 3 channels (RGB)
elif img_array.shape[2] == 4:
img_array = img_array[:, :, :3]
return img_array
# Example usage
processed_img = preprocess_for_ml('empire_state.jpg')
print(f"Processed shape: {processed_img.shape}")This preprocessing function is perfect for preparing images for deep learning models.
Check out Python SciPy Interpolate
Handle Common Errors
When working with image reading functions, you might encounter some common errors:
File Not Found Errors
import os
from PIL import Image
def safe_read_image(file_path):
try:
if os.path.exists(file_path):
return np.array(Image.open(file_path))
else:
print(f"Warning: File not found - {file_path}")
return None
except Exception as e:
print(f"Error reading {file_path}: {e}")
return NoneFormat-Related Errors
from PIL import Image, UnidentifiedImageError
def read_with_format_handling(file_path):
try:
img = Image.open(file_path)
return np.array(img)
except UnidentifiedImageError:
print(f"Unsupported or corrupted image format: {file_path}")
return NoneThese error-handling functions will make your image processing code more robust in production environments.
I hope you found this guide helpful for working with images in Python. While SciPy’s ndimage imread function has been deprecated, the alternatives I’ve covered provide even more functionality and flexibility for your image processing needs.
You may like to read:

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.