Work with PNG binary images in PIL / pillow

When converting PNG binary files from a PIL image object to a numpy array, the values ​​are the same regardless of whether the original image is inverted or not.

For example, both of these images generate identical numpy arrays.

t image t inverted image

import numpy as np
from PIL import Image
t = Image.open('t.png')
t_inverted = Image.open('t_inverted.png')
np.asarray(t)
np.asarray(t_inverted)

output either np.asarray(t)or np.asarray(t_inverted):

array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 1, 1, 0, 0, 1, 1, 0, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 1, 0, 0, 1, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=uint8)

I expected 0s and 1s to be inverted. Why are they the same?

+4
source share
1 answer

Both of these PNG files are indexed. They contain the same data array, but only the values ​​0 and 1 that you see, but these values ​​are not intended for pixel colors. They must be indices in the palette. In the first file, the palette

 Index     RGB Value
   0    [  0,   0,   0]
   1    [255, 255, 255]

and in the second file, the palette

 Index     RGB Value
   0    [255, 255, 255]
   1    [  0,   0,   0]

, Image numpy, .

, convert() Image RGB:

t = Image.open('t.png')
t_rgb = t.convert(mode='RGB')
arr = np.array(t_rgb)
+4

Source: https://habr.com/ru/post/1695587/


All Articles