Converting a PNG image to 2D array
<p>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.</p>

<p>This a B&amp;W image and the pixels are either [255, 255, 255, 255] or [0, 0, 0, 255].</p>

<p>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].</p>

<p>Any ideas how to do a straightforward conversion of this.</p>

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

<pre><code>((arr == 255).all(-1)).astype(int)
</code></pre>

<p>Sample run -</p>

<pre><code>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]])
</code></pre>

python arrays numpy