HOME> 天宫盛宴> PIL.Image 调色板模式处理标签数据

PIL.Image 调色板模式处理标签数据

2025-11-25 03:22:54

文章目录

1 使用PIL.Image库进行调色板模式2 转回原来的色彩3 效果参考

1 使用PIL.Image库进行调色板模式

基本步骤:

自定义调色板,数据格式是一个Nx3的二维数组,一维数组的位置为分类的下标数据类型为np.uint8转化为调色板模式后img.convert("P"),设置调色板即可img.putpalette(bin_colormap)

# 定义调色板的索引

bin_colormap = np.array([[0, 0, 0], [255, 0, 0]]).astype(np.uint8) # 会按照值的循序进行索引

bin_colormap_reverse = np.array([[0, 0, 0], [255, 255, 255]]).astype(np.uint8) # 会按照值的循序进行索引

Example:

def imgRGB2P(src_path, dst_path):

# 定义调色板的索引

bin_colormap = np.array([[0, 255, 0], [255, 0, 0]]).astype(np.uint8) # 会按照值的循序进行索引

bin_colormap_reverse = np.array([[0, 0, 0], [255, 255, 255]]).astype(np.uint8) # 会按照值的循序进行索引

img = Image.open(src_path)

# 转化为p模式

img_p = img.convert("P")

img_p.putpalette(bin_colormap)

img_p.save(dst_path)

2 转回原来的色彩

设置原来的色彩空间,使用调色板模式(单通道的图)进行索引即可

def imgP2RGB(src_path, dst_path):

# 调色板前后的关系为下标对应

bin_colormap = np.array([[0, 255, 0], [255, 0, 0]]).astype(np.uint8) # 会按照值的循序进行索引

bin_colormap_reverse = np.array([[0, 0, 0], [255, 255, 255]]).astype(np.uint8) # 按照索引映射会原图

img = np.array(Image.open(src_path))

# 转化为RGB

img_RGB = bin_colormap_reverse[img]

img_RGB = Image.fromarray(img_RGB).convert("L")

img_RGB.save(dst_path)

3 效果

原图:

自定义调色板,p模式

参考

【PIL】——PIL灰度图以调色板保存成彩图 https://blog.csdn.net/u011622208/article/details/111181378

为什么最终被合并的是琳琅天上,而不是天美呢?这背后没那么简单

2025年《财富》世界500强出炉,中国130家企业上榜