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.

1 Answer 1

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]]
Sign up to request clarification or add additional context in comments.

2 Comments

I cannot use scikit on this project, but I will look at the implementation to better understand as_strided. Thanks!
@Faqinghere As mentioned in the other linked Q&A, you can simply use the source code as standalone without installing scikit-image - github.com/scikit-image/scikit-image/blob/master/skimage/util/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.