Matplotlib colormap从颜色转换为整数

2024-04-20 04:01:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试查看和编辑分类掩码,它们是灰度PNG,值等于类id,即1=class1、2=class2等

Matplotlib colormaps提供了一种从这些整数生成固定调色板的简单方法,可以读取灰度png,应用规格化,应用颜色贴图,按255放大

但是,我该怎么倒退呢?我需要读取图像中的RGB值,从颜色映射中查找它并将其转换回原始整数:(0183255)=2

至RGB:

img_src = Image.open(srcpath + srcfn)
im = np.array(img_src) * 20    #[1,2,3] -> [20,40,60]
im = cm(im)                    #[20,40,60] -> [[0.,0.7196739,1.,1.],...]
im = np.uint8(im * 255)        #[[0.,0.7196739,1.,1.],...] -> [[0,183,255],...]
im = Image.fromarray(im)

从RGB:

im = np.array(img_src) 
im = im/255                    #[[0,183,255],...] -> [[0.,0.7196739,1.,1.],...] 
###The missing step
im = uncm(im)                  #[[0.,0.7196739,1.,1.],...] -> [20,40,60] 
im = im/20                     #[20,40,60] -> [1,2,3]

Tags: imagesrcid编辑imgpng颜色np