Home > Backend Development > Python Tutorial > How to Efficiently Crop Random Image Patches from a 4D Numpy Array using Strided-Based Slicing?

How to Efficiently Crop Random Image Patches from a 4D Numpy Array using Strided-Based Slicing?

Susan Sarandon
Release: 2024-11-03 14:05:03
Original
329 people have browsed it

How to Efficiently Crop Random Image Patches from a 4D Numpy Array using Strided-Based Slicing?

Efficient Numpy Slicing for Random Image Cropping

For efficient cropping of random 16x16 patches from a 4D Numpy array representing multiple color images (where the first dimension is the number of images, and the second and third are the equal width and height), a strided-based approach can be utilized.

Utilizing np.lib.stride_tricks.as_strided or scikit-image's view_as_windows

These methods create sliding windows as views into the input array, reducing memory overhead. Scikit-image's view_as_windows simplifies the setup by specifying the window shape as a tuple whose elements correspond to the dimensions of the input array. Axes for sliding are assigned window lengths, and other axes are set to 1.

Code Example

<code class="python"># Import scikit-image for view_as_windows
from skimage.util.shape import view_as_windows

# Get sliding windows
w = view_as_windows(X, (1,16,16,1))[...,0,:,:,0]

# Generate random per-image offsets
x = np.random.randint(0,12,X.shape[0])
y = np.random.randint(0,12,X.shape[0])

# Index and extract specific windows
out = w[np.arange(X.shape[0]),x,y]

# Reformat if necessary
out = out.transpose(0,2,3,1)</code>
Copy after login

This code generates four random (x_offset, y_offset) pairs and extracts 4 random 16x16 patches within the given parameters, with minimum memory overhead.

The above is the detailed content of How to Efficiently Crop Random Image Patches from a 4D Numpy Array using Strided-Based Slicing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template