'How to I make a image from numpy array in python?

I want to map each numpy array to a color to create an image. For example: if I have the numpy array:

[ [0 0 1 3] 
[0 2 4 5]
[1 2 3 6] ]

I want to make an image by mapping all values below 3 to blue like

[ [blue blue sky-blue green]
[blue sky-blue green green] 
[blue sky-blue green green]


Solution 1:[1]

You can make a two-color color map. Then make an array with 1 or 0 depending on your condition and pass both to pyplot.imshow():

import numpy as np

from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

# white and blue
color = ListedColormap([(1,1,1), (0,0,1)])

a = np.array([
    [0, 0, 1, 3], 
    [0, 2, 4, 5],
    [1, 2, 3, 6] 
])

plt.axis('off')
plt.imshow(a < 3, cmap=color)

enter image description here

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Mark