0
0
SciPydata~5 mins

Image interpolation in SciPy

Choose your learning style9 modes available
Introduction

Image interpolation helps us resize or transform images smoothly by estimating new pixel values.

When you want to enlarge a small photo without making it look blocky.
When you need to rotate or shift an image and keep it clear.
When you want to reduce image size but keep important details.
When you apply filters that require changing image resolution.
When combining images of different sizes into one view.
Syntax
SciPy
from scipy.ndimage import zoom

zoom(input, zoom_factor, order=3)

input: The image array you want to resize.

zoom_factor: How much to scale the image (e.g., 2 means double size).

order: Controls interpolation method (0=nearest, 1=linear, 3=cubic by default).

Examples
Doubles the size of the image using cubic interpolation.
SciPy
zoom(image_array, 2)
Reduces the image size by half using linear interpolation.
SciPy
zoom(image_array, 0.5, order=1)
Scales height by 1 (no change) and width by 2 using nearest neighbor interpolation.
SciPy
zoom(image_array, (1, 2), order=0)
Sample Program

This code creates a small image with one white pixel in the center. Then it enlarges the image by 3 times using cubic interpolation. Finally, it shows both images and prints their sizes.

SciPy
import numpy as np
from scipy.ndimage import zoom
import matplotlib.pyplot as plt

# Create a simple 5x5 grayscale image with a white square in the center
image = np.zeros((5, 5))
image[2, 2] = 1

# Enlarge the image by 3 times using cubic interpolation (order=3)
enlarged_image = zoom(image, 3, order=3)

# Show original and enlarged images side by side
fig, axes = plt.subplots(1, 2, figsize=(6, 3))
axes[0].imshow(image, cmap='gray', interpolation='nearest')
axes[0].set_title('Original Image')
axes[0].axis('off')

axes[1].imshow(enlarged_image, cmap='gray', interpolation='nearest')
axes[1].set_title('Enlarged Image')
axes[1].axis('off')

plt.tight_layout()
plt.show()

# Print shapes to confirm resizing
print(f"Original shape: {image.shape}")
print(f"Enlarged shape: {enlarged_image.shape}")
OutputSuccess
Important Notes

Higher order values give smoother images but take more time to compute.

Nearest neighbor (order=0) is fastest but can look blocky.

Interpolation works on arrays, so color images need to be handled per channel.

Summary

Image interpolation helps resize images smoothly by estimating new pixels.

Use scipy.ndimage.zoom with order to control smoothness.

Try different zoom factors and orders to get the best image quality for your task.