Convert grayscale image to RGB image using matplotlib

How to convert an image in shades of gray M x N, or, in other words, a matrix or a two-dimensional array, into a heat map RGB or, in other words, an array M x N x 3?

Example:

 [[0.9, 0.3], [0.2, 0.1]] 

should become

[[red, green-blue], [green-blue, blue]] 

where red - [1, 0, 0], blue - [0, 0, 1]etc.

+5
source share
1 answer
import matplotlib.pyplot as plt

img = [[0.9, 0.3], [0.2, 0.1]]

cmap = plt.get_cmap('jet')

rgba_img = cmap(img)
rgb_img = np.delete(rgba_img, 3, 2)

cmapis an instance of the matplotlib class LinearSegmentedColormap, which is derived from the class Colormap. It works due to the function __call__defined in Colormap. Here is the docstring link from matplotlib git repo for reference, as it is not described in the API.

def __call__(self, X, alpha=None, bytes=False):
    """
    *X* is either a scalar or an array (of any dimension).
    If scalar, a tuple of rgba values is returned, otherwise
    an array with the new shape = oldshape+(4,). If the X-values
    are integers, then they are used as indices into the array.
    If they are floating point, then they must be in the
    interval (0.0, 1.0).
    Alpha must be a scalar between 0 and 1, or None.
    If bytes is False, the rgba values will be floats on a
    0-1 scale; if True, they will be uint8, 0-255.
    """

- img, plt.imshow plt.matshow, RGB RGBA. ( 30 ).

+13

All Articles