w3resource

Perform Geometric transformations on Synthetic data with NumPy

NumPy: Integration with SciPy Exercise-18 with Solution

Write a Numpy program to generate a dataset and perform SciPy's ndimage geometric transformations (rotation, shift, zoom).

Sample Solution:

Python Code:

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

# Generate a synthetic dataset: a 2D Gaussian blob
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.exp(-(x**2 + y**2))

# Perform geometric transformations
# Rotation by 45 degrees
rotated_z = rotate(z, 45, reshape=False)

# Shift by 10 pixels along both axes
shifted_z = shift(z, shift=[10, 10])

# Zoom by a factor of 2
zoomed_z = zoom(z, zoom=2)

# Plot the original and transformed datasets
fig, axs = plt.subplots(2, 2, figsize=(10, 10))

# Original dataset
axs[0, 0].imshow(z, extent=[-5, 5, -5, 5])
axs[0, 0].set_title('Original')

# Rotated dataset
axs[0, 1].imshow(rotated_z, extent=[-5, 5, -5, 5])
axs[0, 1].set_title('Rotated')

# Shifted dataset
axs[1, 0].imshow(shifted_z, extent=[-5, 5, -5, 5])
axs[1, 0].set_title('Shifted')

# Zoomed dataset
axs[1, 1].imshow(zoomed_z, extent=[-5, 5, -5, 5])
axs[1, 1].set_title('Zoomed')

plt.tight_layout()
plt.show()

Output:

Perform Geometric transformations on Synthetic data with NumPy

Explanation:

  • Import libraries:
    • Import necessary modules from NumPy, SciPy, and Matplotlib.
  • Generate synthetic dataset:
    • Create a 2D Gaussian blob using NumPy's meshgrid and exponential functions.
  • Perform geometric transformations:
    • Rotation: Rotate the dataset by 45 degrees using SciPy's rotate function.
    • Shift: Shift the dataset by 10 pixels along both axes using SciPy's shift function.
    • Zoom: Zoom into the dataset by a factor of 2 using SciPy's zoom function.
  • Plot datasets:
    • Use Matplotlib to visualize the original and transformed datasets in a 2x2 grid layout.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Create a 2D grid and solve a PDE with NumPy and SciPy.
Next: Fit a statistical model using MLE with NumPy and SciPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/perform-geometric-transformations-on-synthetic-data-with-numpy.php