0

I have a PNG file which when I convert the image to a numpy array, it is of the format that is 184 x 184 x 4. The image is 184 by 184 and each pixel is in RGBA format and hence the 3D array.

This a B&W image and the pixels are either [255, 255, 255, 255] or [0, 0, 0, 255].

I want to convert this to a 184 x 184 2D array where the pixels are now either 1 or 0, depending upon if it is [255, 255, 255, 255] or [0, 0, 0, 255].

Any ideas how to do a straightforward conversion of this.

2 Answers 2

1

There would be several ways to do the comparison to give us a boolean array and then, we just need to convert to int array with type conversion. So, for the comparison, one simple way would be to compare against 255 and check for ALL matches along the last axis. This would correspond to checking for [255, 255, 255, 255]. Thus, one approach would be like so -

((arr == 255).all(-1)).astype(int)

Sample run -

In [301]: arr
Out[301]: 
array([[[255, 255, 255, 255],
        [  0,   0,   0, 255],
        [  0,   0,   0, 255]],

       [[  0,   0,   0, 255],
        [255, 255, 255, 255],
        [255, 255, 255, 255]]])

In [302]: ((arr == 255).all(-1)).astype(int)
Out[302]: 
array([[1, 0, 0],
       [0, 1, 1]])
Sign up to request clarification or add additional context in comments.

Comments

1

If there are really only two values in the array as you say, simply scale and return one of the dimensions:

(arr[:,:,0] / 255).astype(int)

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.