简体   繁体   中英

Convert Numpy array to image

I have a little nasty problem. I have a numpy array filled with float values. The background is that the array's values represent the water depth of a square grid.

345.34 888.78 999.35
300.00  98.00  88.45
440.89 423.56  11.68

I want to convert/save this array as image. Thereby, a range of values shall be represented by one color.

"dark blue" "midnight blue" "midnight blue"       #00008B #191970 #191970
"dark blue" "medium blue"   "medium blue"    or   #00008B #0000CD #0000CD 
"navy"      "navy"          "blue"                #000080 #000080 #0000FF

I circumvented this problem by saving the array as ASCII file and converting it in ArcGIS to a raster map but I want to avoid ArcGIS since I have too many arrays/maps to do it manually.

My attempt was to replace a range of values with integers through masks. Then I convert the replaced float values to strings and replace the strings with the RGB color codes. I finally use Image.fromarray to create an image. The result is a mess. It does not resemble an inundation map.

I hope somebody knows a doable way.

You can achieve that simply passing your data to matplotlib.pyplot.imshow() . The color scale can be adjusted by the color map of your choice. Assuming you have the data saved in a text file:

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt

data = np.loadtxt('data.txt')
plt.imshow(data, cmap=cm.Blues)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM