Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert mask (boolean) array to list of x,y coordinates

Tags:

python

numpy

I have a 'mask' (boolean) 2D array and I would like to transform it into a list of coordinates. What's the proper numpythonic way to do that ?

The input would be something like this:

[[False,False,True],
 [False,True,False]]

and given the above input, the output should be:

[(0,2),(1,1)]
like image 417
nicoco Avatar asked Feb 11 '16 13:02

nicoco


1 Answers

Use

  • np.where: Can be used if you want to index another array later with it. But the result is not quite what you specified.
  • np.argwhere: If you want your specified result. But this result cannot be used for indexing another array.

Some example code:

import numpy as np
a = np.array([[False,False,True],
              [False,True,False]])
np.argwhere(a) # equivalent to checking a == True
#array([[0, 2],
#       [1, 1]], dtype=int64)
np.where(a) # equivalent to checking a == True
#(array([0, 1], dtype=int64), array([2, 1], dtype=int64))

And if you want to convert your result to a list there is a ndarray.tolist() method. So you can call np.argwhere(a).tolist().

like image 183
MSeifert Avatar answered Oct 23 '22 17:10

MSeifert