One of the common tasks in image processing, computer vision, and other scientific applications is to extract smaller contiguous blocks from a larger block or image. This process is known as block processing or block-based image processing. In this article, we’ll use NumPy to extract contiguous smaller blocks from a larger block efficiently.
1. Using “nested loops”:
In this code, we create a new array C
with the desired shape and then use nested for-loops to fill it with sub-arrays of Z
. We iterate over all possible starting positions of the sub-arrays and use slicing to extract them. The resulting sub-arrays are then copied into the corresponding positions of C
. Note that we also initialize C
with zeros of the same data type as Z
, so that the resulting array has the correct type.
2. Using “np.lib.stride_tricks.sliding_window_view()”:
This code creates a sliding window view of an array Z
with shape (10,10)
and fills it with random integers between 0
and 5
. The sliding window view is created using the np.lib.stride_tricks.sliding_window_view()
method with a window size of (n,n)
, where n
is 3 in this case. The resulting view C
has shape (8,8,3,3)
since there are 8 possible positions along each dimension of the original array Z
to place a sliding window of size (3,3)
. Each element of C
is a (3,3)
window view of Z
. The print
statement displays the shape of C
.