Extract multiple windows/patches from an (image) array, as defined in another array



I have an image im which is an array as given by imread. Say e.g.

im = np.array([[1,2,3,4],

I have another (n,4) array of windows where each row defines a patch of the image as (x, y, w, h). E.g.

windows = np.array([[0,0,2,2],

I’d like to extract all of these patches from im as sub-arrays without looping through. My current looping solution is something like:

for x, y, w, h in windows:
    patch = im[y:(y+h),x:(x+w)]

But I’d like a nice array-based operation to get all of them, if possible.






For same window sizes, we could get views with help from scikit-image’s view_as_windows, like so –

from skimage.util.shape import view_as_windows

im4D = view_as_windows(im, (windows[0,2],windows[0,3]))
out = im4D[windows[:,0], windows[:,1]]

Sample run –

In [191]: im4D = view_as_windows(im, (windows[0,2],windows[0,3]))

In [192]: im4D[windows[:,0], windows[:,1]]
array([[[1, 2],
        [2, 3]],

       [[3, 4],
        [4, 5]]])


Facebook Comments

Post a comment