How to convert a Label matrix to colour matrix for image segmentation?

独自空忆成欢 提交于 2020-01-02 19:20:11

问题


I have a label matrix of 256*256 for example. And the classes are 0-11 so 12 classes. I want to convert the label matrix to colour matrix. I tried do it in a code like this

`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]
            `

It is highly inefficient. PS: the shape of x is [256 256] and dummy is [256 256 3]. Is there any better way to do it ?


回答1:


You are looking into indexed RGB images - an RGB image where you have a fixed "pallet" of colors, each pixel indexes to one of the colors of the pallet. See this page for more information.

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()


来源:https://stackoverflow.com/questions/54928522/how-to-convert-a-label-matrix-to-colour-matrix-for-image-segmentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!