deleting certain entries in numpy array

Robert Kern robert.kern at gmail.com
Wed Jul 1 14:33:53 EDT 2009


On 2009-07-01 09:51, Sebastian Schabe wrote:
> Hello everybody,
>
> I'm new to python and numpy and have a little/special problem:

You will want to ask numpy questions on the numpy mailing list.

   http://www.scipy.org/Mailing_Lists

> I have an numpy array which is in fact a gray scale image mask, e.g.:
>
> mask =
> array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 255, 255, 255, 0, 0, 255, 0],
> [ 0, 0, 255, 255, 255, 0, 0, 255, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0],
> [ 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8)
>
> and I have another array of (y, x) positions in that mask (first two
> values of each row):
>
> pos =
> array([[ 3., 2., 0., 0.],
> [ 3., 4., 0., 0.],
> [ 5., 2., 0., 0.],
> [ 5., 4., 0., 0.],
> [ 6., 2., 0., 0.],
> [ 6., 7., 0., 0.],
> [ 0., 0., 0., 0.],
> [ 8., 8., 0., 0.]])
>
> and now I only want to keep all lines from 2nd array pos with those
> indices that are nonzero in the mask, i.e. line 3-6 (pos[2]-pos[5]).
>
> F.e. line 4 in pos has the values (5, 4) and mask[5][4] is nonzero, so I
> want to keep it. While line 2 (pos[1]) has the values (4, 6) and
> mask[4][6] is zero, so shall be discarded.
>
> I want to avoid a for loop (if possible!!!) cause I think (but don't
> know) numpy array are handled in another way. I think numpy.delete is
> the right function for discarding the values, but I don't know how to
> build the indices.

First, convert the pos array to integers, and just the columns with indices in them:

   ipos = pos[:,:2].astype(int)

Now check the values in the mask corresponding to these positions:

   mask_values = mask[ipos[:,0], ipos[:,1]]

Now extract the rows from the original pos array where mask_values is nonzero:

   result = pos[mask_values != 0]

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list