Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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

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

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],
                    [1,1,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.

Thanks.

like image 715
J. Doe Avatar asked Nov 07 '22 14:11

J. Doe


1 Answers

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]]
Out[192]: 
array([[[1, 2],
        [2, 3]],

       [[3, 4],
        [4, 5]]])
like image 137
Divakar Avatar answered Nov 14 '22 22:11

Divakar