I have a large size 2d numpy array (size = (2000, 2000)) with only five possible values 1.0, 2.0, 3.0, 4.0 and 5.0. I want to save and show this array as an image in RGB colored format, here each unique value of array should be represented by different color. Please help i am a beginner to python.
2 Answers
You could use PIL.Image to do that, but first transform your array.
You could say for example, that:
- 1.0 Should be red, represented as (255,0,0)
- 2.0 Should be green -> (0,255,0)
- 3.0 Should be blue -> (0,0,255)
- 4.0 Should be black -> (0,0,0)
- 5.0 Should be white -> (255,255,255)
You could of course change those values to whatever colors you choose, but this is just for demonstration. That being said, your 2-d array also needs to be "flattened" to 1-d for PIL.Image to accept it as data.
from PIL import Image
import numpy as np
your_2d_array = np.something() # Replace this line, obviously
img_array = []
for x in your_2d_array.reshape(2000*2000):
if x == 1.0:
img_array.append((255,0,0)) # RED
elif x == 2.0:
img_array.append((0,255,0)) # GREEN
elif x == 3.0:
img_array.append((0,0,255)) # BLUE
elif x == 4.0:
img_array.append((0,0,0)) # BLACK
elif x == 5.0:
img_array.append((255,255,255)) # WHITE
img = Image.new('RGB',(2000,2000))
img.putdata(img_array)
img.save('somefile.png')
While this should work, I think there are more efficient ways to do this that I do not know, So I will be glad if someone edits this answer with better examples. But if it's a small app and maximum efficiency doesn't bother you, here it is.
Comments
matplotlib is useful for tasks like this, though there are other ways.
Here's an example:
import numpy as np
import matplotlib.image
src = np.zeros((200,200))
print src.shape
rgb = np.zeros((200,200,3))
print rgb.shape
src[10,10] = 1
src[20,20] = 2
src[30,30] = 3
for i in range(src.shape[0]):
for j in range(src.shape[1]):
rgb[i,j,0] = 255 if src[i,j]==1 else 0 # R
rgb[i,j,1] = 255 if src[i,j]==2 else 0 # G
rgb[i,j,2] = 255 if src[i,j]==3 else 0 # B
matplotlib.image.imsave('test.png', rgb.astype(np.uint8))
The trick is to convert it to an RGB array of shape (x, y, 3). You can use any formula you want to gen the per-pixel RGB values.
Also, note converting it to an uint8 array.