Assuming that your image is a single-channel image rather than a three-channel image, the required task can be performed by defining a palette that maps indices (e.g. gray level intensities or picture values) into colors:
import numpy as np
import matplotlib.pyplot as plt
palette = np.array([[ 0, 0, 0], # black
[255, 0, 0], # red
[ 0, 255, 0], # green
[ 0, 0, 255], # blue
[255, 255, 255]]) # white
I = np.array([[ 0, 1, 2, 0], # 2 rows, 4 columns, 1 channel
[ 0, 3, 4, 0]])
Image conversion is efficiently accomplished through NumPy's broadcasting:
RGB = palette[I]
And this is how the transformed image looks like:
>>> RGB
array([[[ 0, 0, 0], # 2 rows, 4 columns, 3 channels
[255, 0, 0],
[ 0, 255, 0],
[ 0, 0, 0]],
[[ 0, 0, 0],
[ 0, 0, 255],
[255, 255, 255],
[ 0, 0, 0]]])
plt.imshow(RGB)
cmap = plt.get_cmap('spring')
to get the cmap object instead ofmatplotlib.cm.spring
– Stealage