'Converting numpy array into an RGB image using PILLOW

I have a numpy array of dimension 11*11 that I want to convert into an RGB image so I'm using this code :

import matplotlib.pyplot as plt
from PIL import Image as im
n_images = 1
train_data_np = train_data.to_numpy()
train_images = train_data_np[:n_images]
for i in range(n_images):
    image_train = np.reshape(train_images[i], [11, 11])
    image = im.fromarray(np.uint8(image_train))
    plt.imshow(image)
    plt.show()

My problem is that the image displayed is not all RGB because for this value :

[[  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0 255   0   0 150  25  43   7  43   0]
 [  0   0  12   0   0 255   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0 255   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0   0   0]
 [  0   0   0   0   0   0   0   0   0 255   0]]

it displayed this imageenter image description here

which doesn't respect RGB format as you can see where 0 it should be black instead of purple and 255 should be white instead of yellow. I tried to convert the numpy array of [11,11] into [11,11,3] to support RGB channels but it gave in the end a grayscale image only white and black. but it is not what I want. Here is the code that I used :

n_images = 1
train_data_np = train_data.to_numpy()
train_images = train_data_np[:n_images]
for i in range(n_images):
    image_res = np.reshape(train_images[i],[11,11])
    img2 = np.zeros( ( image_res.shape[0], image_res.shape[1], 3 ) )
    img2[:,:,0] = image_res # same value in each channel
    img2[:,:,1] = image_res
    img2[:,:,2] = image_res
    image_train = np.reshape(img2,[11,11,3])
    image = im.fromarray(np.uint8(image_train),'RGB')
    plt.imshow(image)
    plt.show()

can someone explain to me how to implement or use a python function to transform the NumPy array 11x11 into an array of 11x11x3 using a colormap ? This link contains an example of what i want really to do :

https://www.mathworks.com/help/matlab/ref/ind2rgb.html

Thank you in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source