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

I have an im image, which is the array given by imread . Say for example

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

I have another array of (n,4) windows , where each line defines the image patch as (x, y, w, h) . For instance.

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

I would like to extract all these fixes from im as sub-arrays without scrolling. My current looping solution is something like:

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

But I need a good array-based operation to get all of them, if possible.

Thanks.

+3
source share
2 answers

With the same window size, we can get a view using scikit-image view_as_windows , for example:

 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]] 

Run Example -

 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]]]) 
+1
source

If scikit not available, we can resolve the @Divakar solution with numpy.lib.stride_tricks . The same restriction (all windows should have the same shape):

 import numpy as np from numpy.lib.stride_tricks import as_strided im = np.array([[1,2,3,4], [2,3,4,5], [3,4,5,6], [4,5,6,7]]) windows = np.array([[0,0,2,2], [1,1,2,2]]) Y, X = im.shape y, x = windows[0, 2:] cutmeup = as_strided(im, shape=(Y-y+1, X-x+1, y, x), strides=2*im.strides) print(cutmeup[windows[:, 0], windows[:, 1]]) 

Output:

 [[[1 2] [2 3]] [[3 4] [4 5]]] 
0
source

Source: https://habr.com/ru/post/1274880/


All Articles