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 ?

Shai
  • 111,146
  • 38
  • 238
  • 371
Farshid Rayhan
  • 1,134
  • 4
  • 17
  • 31

1 Answers1

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()
Shai
  • 111,146
  • 38
  • 238
  • 371
  • is '255, 255, 255' suppose to be in a list like [ [255, 255, 255] , [ 255, 255, 0 ] , ... ] ? – Farshid Rayhan Mar 01 '19 at 13:48
  • @FarshidRayhan please see the link in the answer – Shai Mar 01 '19 at 14:30
  • @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? – Muhammad Yasirroni Jun 30 '21 at 01:03