How to convert a Label matrix to colour matrix for image segmentation?
Asked Answered
W

1

4

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 ?

Weeds answered 28/2, 2019 at 14:59 Comment(0)
B
4

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()
Bivalent answered 28/2, 2019 at 16:3 Comment(3)
is '255, 255, 255' suppose to be in a list like [ [255, 255, 255] , [ 255, 255, 0 ] , ... ] ?Weeds
@FarshidRayhan please see the link in the answerBivalent
@FarshidRayhan https://effbot.org/ is in Hiatus. What kind of information that we might miss from your answer? Anyway, is there rainbow palette generator based on number of classes for this kind of problem?Lopes

© 2022 - 2024 — McMap. All rights reserved.