Life rocks
Life rocks

Reputation: 21

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]

Upvotes: 2

Views: 293

Answers (1)

Mark
Mark

Reputation: 92440

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

Upvotes: 2

Related Questions