Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting coordinates from a numpy array

so maybe this is a basic question about numpy, but I can't see how to do is, so lets say I have a 2D numpy array like this

import numpy as np

arr = np.array([[  0., 460., 166., 167., 123.],
                [  0.,   0.,   0.,   0.,   0.],
                [  0.,  81.,   0.,  21.,   0.],
                [  0., 128.,  23.,   0.,  12.],
                [  0.,  36.,   0.,  13.,   0.]])

And I want the coordinates from the subarray

[[0., 21,.  0.],
 [23., 0., 12.],
 [0., 13.,  0.]]

I tried slicing my original array and the find the coordinates using np.argwhere like this

newarr = np.argwhere(arr[2:, 2:] != 0)

#output
#[[0 1]
# [1 0]
# [1 2]
# [2 1]]

Which are indeed the coordinates from the subarray but I was expecting the coordinates corresponding to my original array, the desired output is:

[[2 3]
 [3 2]
 [3 4]
 [4 3]]

If I use the np.argwhere with my original array I get a bunch of coordinates that I don't need, so I can't figure it out how to get what I need, any help or if you can point me to the right direction will be great, thank you!

like image 541
Carlos Eduardo Corpus Avatar asked Aug 06 '26 20:08

Carlos Eduardo Corpus


1 Answers

Assume origin on the top left corner of the matrix and the matrix itself placed in 4th quadrant of Cartesian space. The horizontal axis having the column indices, and the vertical axis coming down having row indices.

You will see the whole sub-matrix is origin shifted on (2,2) coordinate. Thus when the coordinates you get are with respect to sub-matrix on origin, then to get them back to (2,2) again, just add (2,2) in whole elements:

>>> np.argwhere(arr[2:, 2:] != 0) + [2, 2]
array([[2, 3],
       [3, 2],
       [3, 4],
       [4, 3]])

For other examples:

>>> col_shift, row_shift = 3, 2

>>> arr[row_shift:, col_shift:]
array([[21.,  0.],
       [ 0., 12.],
       [13.,  0.]])

>>> np.argwhere(arr[row_shift:, col_shift:] != 0) + [row_shift, col_shift]
array([[2, 3],
       [3, 4],
       [4, 3]])

For a fully inside sub matrix, you can bound the column and rows:

>>> col_shift, row_shift = 0, 1
>>> col_bound, row_bound = 4, 4

>>> arr[row_shift:row_bound, col_shift:col_bound]
array([[  0.,   0.,   0.,   0.],
       [  0.,  81.,   0.,  21.],
       [  0., 128.,  23.,   0.]])

>>> np.argwhere(arr[row_shift:row_bound, col_shift:col_bound] != 0) + [row_shift, col_shift]
array([[2, 1],
       [2, 3],
       [3, 1],
       [3, 2]])
like image 157
Vicrobot Avatar answered Aug 10 '26 09:08

Vicrobot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!