例如,我的标签矩阵为256 * 256。班级是0-11,所以12个班级我想将标签矩阵转换为颜色矩阵。我试图用这样的代码
`for i in range(256):
for j in range(256):
if x[i][j] == 11:
dummy[i][j] = [255,255,255]
if x[i][j] == 1:
dummy[i][j] = [144,0,0]
if x[i][j] == 2:
dummy[i][j] = [0,255,0]
if x[i][j] == 3:
dummy[i][j] = [0,0,255]
if x[i][j] == 4:
dummy[i][j] = [144,255,0]
if x[i][j] == 5:
dummy[i][j] = [144,0,255]
if x[i][j] == 6:
dummy[i][j] = [0,255,255]
if x[i][j] == 7:
dummy[i][j] = [122,0,0]
if x[i][j] == 8:
dummy[i][j] = [0,122,0]
if x[i][j] == 9:
dummy[i][j] = [0,0,122]
if x[i][j] == 10:
dummy[i][j] = [122,0,122]
if x[i][j] == 11:
dummy[i][j] = [122,122,0]
`
效率极低。 PS:x的形状为[256 256],虚拟值为[256 256 3]。有什么更好的方法吗?
答案 0 :(得分:2)
您正在寻找索引的RGB图像-RGB图像,其中具有固定的“调色板”颜色,每个像素都索引到调色板的一种颜色。有关更多信息,请参见this page。
from PIL import Image
img = Image.fromarray(x, mode="P")
img.putpalette([
255, 255, 255, # index 0
144, 0, 0, # index 1
0, 255, 0, # index 2
0, 0, 255, # index 3
# ... and so on, you can take it from here.
])
img.show()