asheets
asheets

Reputation: 870

Use numpy to make mask array for pixels of certain value

In processing an image, I would like to ignore all white pixels. I figure the best way to do this is to set the mask array to change the mask array where there are white pixels as soon as I initialize it. To do this I use the method described on the last line of the following code.

with PIL.Image.open(picture) as im:
    pix = numpy.array(im, dtype=numpy.float)
[height, width, _] = pix.shape
mask = numpy.zeros((height,width))
mask[numpy.argwhere(pix == [255,255,255])] = 1

However, this line generates the following error:

  File "C:\Users\Alec\zone_map.py", line 19, in zone_map
    mask[numpy.argwhere(pix == [255,255,255])] = 1

IndexError: index 5376 is out of bounds for axis 0 with size 4000

How can I change this to accomplish the desired result?

Upvotes: 2

Views: 2148

Answers (1)

Divakar
Divakar

Reputation: 221684

Use a mask of ALL-reduced along the last axis and simply index into input array to assign value(s) following boolean-indexing, like so -

mask = (pix==255).all(axis=-1)
pix[mask] = 1

Sample run -

In [18]: pix
Out[18]: 
array([[[  5,  11,  10],
        [  9,   5,  11],
        [ 11,  10,   9],
        [255, 255, 255]],

       [[  9,   8,   8],
        [ 10,   8,   9],
        [255, 255, 255],
        [  5,   8,  10]]])

In [19]: mask = (pix==255).all(-1)

In [21]: pix[mask] = 1

In [22]: pix
Out[22]: 
array([[[ 5, 11, 10],
        [ 9,  5, 11],
        [11, 10,  9],
        [ 1,  1,  1]],

       [[ 9,  8,  8],
        [10,  8,  9],
        [ 1,  1,  1],
        [ 5,  8, 10]]])

Upvotes: 4

Related Questions