-
from PIL import Image
import numpy as np
palette = np.random.random_integers(0, 255, size=(256,4)).astype(np.uint8)
indices = np.random.random_integers(0, 255, size=(20, 10)).astype(np.uint16)
img = Image.fromarray(indices, mode='PA')
img.putpalette(palette) Running it with PIL 11.3.0 gives In unpack.c https://github.com/python-pillow/Pillow/blob/9fd4af55f773110edaaca75905568bf8d805eea0/src/libImaging/Unpack.c#L1604C1-L1607C32 I see
which are used in Line 1764 in 9fd4af5 unpack = ImagingFindUnpacker(palette_mode, rawmode, &bits);
if (!unpack) {
PyErr_SetString(PyExc_ValueError, wrong_raw_mode);
return NULL;
}
if (palettesize * 8 / bits > 256) {
PyErr_SetString(PyExc_ValueError, wrong_palette_size);
return NULL;
} If I read that right, palettes are expected to be 16 bits per color? How does that work with RGBA? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
I will attempt to explain, let me know if there is any confusion left aftewards. PA images do not necessarily have a palette that includes alpha values. They have two separate values for each pixel, the palette index (P) and the alpha value (A). For each 16 bit pixel, 8 bits describe the palette index (0-255) and 8 bits describe an independent alpha value. So you can combine any palette index with any alpha value. In Pillow, palettes can be in RGBA mode, containing 256 RGBA colours. I suggest using img = Image.fromarray(indices, mode='P')
img.putpalette(palette, 'RGBA') |
Beta Was this translation helpful? Give feedback.
I will attempt to explain, let me know if there is any confusion left aftewards.
PA images do not necessarily have a palette that includes alpha values. They have two separate values for each pixel, the palette index (P) and the alpha value (A). For each 16 bit pixel, 8 bits describe the palette index (0-255) and 8 bits describe an independent alpha value. So you can combine any palette index with any alpha value.
In Pillow, palettes can be in RGBA mode, containing 256 RGBA colours. I suggest using
img.putpalette(palette, 'RGBA')
. See https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.putpalette. So you probably want