0
0
SciPydata~5 mins

Image rotation and zoom in SciPy

Choose your learning style9 modes available
Introduction

We rotate and zoom images to change their angle or size. This helps us see images from different views or focus on details.

You want to rotate a photo to fix its angle.
You need to zoom in on a part of an image to see details better.
You want to prepare images for machine learning by standardizing their size and orientation.
You want to create effects by rotating or zooming images in a project.
Syntax
SciPy
from scipy.ndimage import rotate, zoom

rotated_image = rotate(image, angle, reshape=True)
zoomed_image = zoom(image, zoom_factor)

image is a NumPy array representing the image.

angle is in degrees. Positive values rotate counter-clockwise.

Examples
Rotate image 45 degrees and zoom to double size.
SciPy
rotated = rotate(image, 45)
zoomed = zoom(image, 2)
Rotate image 90 degrees clockwise without changing shape, zoom to half size.
SciPy
rotated = rotate(image, -90, reshape=False)
zoomed = zoom(image, 0.5)
Sample Program

This code creates a simple black and white image, rotates it 45 degrees, and zooms it by 2 times. Then it shows all three images side by side.

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

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

# Rotate the image 45 degrees
rotated_image = rotate(image, 45, reshape=True)

# Zoom the image by 2 times
zoomed_image = zoom(image, 2)

# Show original, rotated, and zoomed images
fig, axs = plt.subplots(1, 3, figsize=(9,3))
axs[0].imshow(image, cmap='gray')
axs[0].set_title('Original')
axs[0].axis('off')

axs[1].imshow(rotated_image, cmap='gray')
axs[1].set_title('Rotated 45°')
axs[1].axis('off')

axs[2].imshow(zoomed_image, cmap='gray')
axs[2].set_title('Zoomed x2')
axs[2].axis('off')

plt.tight_layout()
plt.show()
OutputSuccess
Important Notes

Rotation can change the image size if reshape=True. Set it to False to keep original size but parts may be cut off.

Zooming can make images bigger or smaller. Zoom factors >1 enlarge, <1 shrink.

Images are NumPy arrays, so you can use other NumPy tools to prepare or analyze them.

Summary

Use scipy.ndimage.rotate to turn images by any angle.

Use scipy.ndimage.zoom to resize images smoothly.

These tools help change how images look for analysis or display.