1

Given an Nx2 array of N points ([row, col]):

points = np.array([
  [r1, c1],
  [r2, c2],
  ...
])

And given a 2D matrix I want to operate on:

img = np.arange(400).reshape(20,20)

I'm looking for an efficient way to take 2D slices of img using the indices.

So if I want a slice of a given height h and width w, the pseudocode would be:

p_rows = points[:,0]
p_cols = points[:,1]
patches = img[p_rows:p_rows+h, p_cols:p_cols+w]

Such that the result would be an Nxhxw matrix. But, alas, broadcasting didn't save me this time.

I've looked at np.r_, np.select, np.lib.stride_tricks.as_strided, np.take... But not had any luck yet.

Braiam
  • 1
  • 11
  • 47
  • 78
Faqinghere
  • 101
  • 1
  • 6

1 Answers1

1

We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows. More info on use of as_strided based view_as_windows. Then, indexing into those windows with advanced-indexing using those indices from points solves it for us!

from skimage.util.shape import view_as_windows

w = view_as_windows(img,(h,w))
out = w[points[:,0],points[:,1]]
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • I cannot use scikit on this project, but I will look at the implementation to better understand as_strided. Thanks! – Faqinghere Mar 09 '20 at 08:38
  • 1
    @Faqinghere As mentioned in the other linked Q&A, you can simply use the source code as standalone without installing scikit-image - https://github.com/scikit-image/scikit-image/blob/master/skimage/util/shape.py. – Divakar Mar 09 '20 at 08:39