简体   繁体   中英

Converting a PNG image to 2D array

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.

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]])

如果您所说的数组中实际上只有两个值,则只需缩放并返回其中一个维:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM