0

So I've tried a number of methods combining or using alone r_, s_, stride tricks, slicing tricks, _ix, and similar and I haven't been able to vectorize what I'm trying to do here.

In summary, given a 2d array, an Nx2 array of coordinates, and a window shape (h,w) how can I, in one pass no loops, extract an Nxhxw array of submatrices from the original array. It's easy to do in a for loop but in practice I'm dealing with many hundreds of coordinates and a window shape of (50,50) in a large image, so yeah vectorization for speed. Caveat, only Numpy, NO scipy.

As an example:

arr:
array([[13, 11,  7,  6,  6,  6,  4,  5,  3, 12],
       [13,  1,  8,  7, 12,  3,  3, 15,  4,  8],
       [10, 12,  2,  1,  6,  3, 11,  5, 15,  4],
       [ 1,  2, 13, 12, 10,  7,  7, 11, 12,  2],
       [ 3,  1, 11,  8,  5, 11,  9,  6,  8,  6],
       [ 9,  7,  1,  9,  2,  3,  6,  5,  7, 12],
       [13,  7,  6,  1,  6,  3, 13,  3, 12,  8],
       [ 1,  9,  3, 15,  6,  4,  9, 15,  2,  6],
       [ 9,  2,  8, 12,  3, 11,  7, 12, 15, 14],
       [13, 15,  9, 14, 14, 14,  1, 11,  6, 15]])
coords:
array([[9,  3],
       [5,  2],
       [ 5,  6],
       [ 1,  4],
       [ 0,  6]])
window = (3,3)
submatrics_at_points(arr,coords,window):
array([[[8,12,3],
        [9,14,14],
        [nan,nan,nan]],
       [[1,11,8],
        [7,1,9],
        [7,6,1]],
       [[11,9,6],
        [3,6,5],
        [3,13,3]],
       [[6,6,6],
        [7,12,3],
        [1,6,3]],
       [[nan,nan,nan],
        [6,4,5],
        [3,3,15]],])
  • Pad with `NaNs` around the border and use this Q&A - https://stackoverflow.com/questions/52642035/. – Divakar Mar 06 '19 at 17:31
  • Explore your options. 1) iterate on `coords` fetching each submatrix (with slice?), stack the results. 2) iterate on coords creating index arrays; do one `arr` indexing. 3) get strided windows, select the subset. The `nan` fill could complicate all of these. – hpaulj Mar 06 '19 at 17:37
  • @Divakar, I did come across that Q&A earlier. I need to read it more carefully. Just need to be very careful of memory overflow errors. hpaulj, I am attempting to do this without iteration because it's a subfunction that's already in a for loop. – Alex Matthers Mar 06 '19 at 22:27

0 Answers0