Why is a palette mask's pixel value different from its display color?

A P-mode pixel stores an index. getpalette exposes the color table that gives the index its displayed color.

Pixel experiment and interpretation

Assign red to class 1. Sampling still gives label 1, while RGB conversion yields the red triplet. Preserve indices for training targets.

from PIL import Image

im=Image.new('P',(1,1),1)
im.putpalette([0,0,0,255,0,0])
(im.getpixel((0,0)),im.getpalette()[3:6],im.convert('RGB').getpixel((0,0)))

Result (1, [255, 0, 0], (255, 0, 0))

中文

调色板标签图的像素值为何不是显示颜色?

P 模式的像素保存调色板索引,getpalette 可读出索引对应的颜色表。

像素实验与适用边界

给标签 1 配上红色,直接采样仍是类别 1,转成 RGB 后才能读到红色三元组。存训练标签时要保留索引。

from PIL import Image

im=Image.new('P',(1,1),1)
im.putpalette([0,0,0,255,0,0])
(im.getpixel((0,0)),im.getpalette()[3:6],im.convert('RGB').getpixel((0,0)))

结果 (1, [255, 0, 0], (255, 0, 0))

References / 参考来源

Keep reading / 继续阅读