2

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?

1
  • 1
    What do you mean by "doesn't work"? Does it throw an error? Give an unexpected result? Commented Sep 14, 2017 at 22:04

1 Answer 1

4

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]]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.