2

I have loaded image as a numpy array using pillow and the dimensions of the resulting numpy array is (184, 184, 4), i.e it's a 184x184 pixel image with each pixel having RGBA dimensions.

For all practical purposes my application just needs to know if a pixel is black or not and hence I just need a 184x184 np array with 0, 1's.

I am new to numpy and particularly image manipulation, wanted to know if there is a faster method to do it.

I tried the naive implementation of checking each pixel in a loop, which appears to be too costly.

1 Answer 1

4

If I understand correctly, you have an array with shape (184,184,4) and you want to get a boolean array with shape (184,184) depending on whether the final dimension is equal to [0,0,0,0]

image = np.random.randint(0, 255, size=(184, 184, 4)) #Generate random image
isBlack = np.int64(np.all(image[:, :, :3] == 0, axis=2))

Done!

But how does it work? It seems like magic! Numpy is kind of magical. That's why we like it. In this case:

  • the image==0 converts to a (184,184,4) boolean array depending on whether each number is equal to 0
  • in this case we use image[:,:,:3] to exclude the 4th number from the equation
  • the np.all asks whether all the elements are equal to 0.
  • the axis parameter changes the axis that it looks at, remembering that python starts counting at 0, so the third axis is number 2.
Sign up to request clarification or add additional context in comments.

6 Comments

what if I want 0 or 1 instead of True or false.
isBlack = np.int16((np.all(image==0,axis=2)))
Also I want the final dimension to be equal to [0,0,0,<I don't care about this place>]
Although I don't know why you would want it that way. The True / False is useful for masking other arrays
The reason being the last pixel value is transparency in the image and I don't care about it, at all. I'd be glad if you can provide a simple example of masking.
|

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.