deleting certain entries in numpy array

Sebastian Schabe sebastian.schabe at gmx.de
Wed Jul 1 16:51:47 CEST 2009


Hello everybody,

I'm new to python and numpy and have a little/special problem:

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.



Maybe someone can help me with that or suggest which way to do this

Sebastian



More information about the Python-list mailing list