Matplotlib/converting_a_matrix_to_a_raster_image - SciPy wiki dump (original) (raw)

Scipy provides a command (imsave) to make a raster (png, jpg...) image from a 2D array, each pixel corresponding to one value of the array. Yet the image is black and white.

Here is a recipy to do this with Matplotlib, and use a colormap to give color to the image.

1 from pylab import * 2 from scipy import mgrid 3 4 def imsave(filename, X, kwargs): 5 """ Homebrewed imsave to have nice colors... """ 6 figsize=(array(X.shape)/100.0)[::-1] 7 rcParams.update({'figure.figsize':figsize}) 8 fig = figure(figsize=figsize) 9 axes([0,0,1,1]) 10 axis('off') 11 fig.set_size_inches(figsize) 12 imshow(X,origin='lower', kwargs) 13 savefig(filename, facecolor='black', edgecolor='black', dpi=100) 14 close(fig) 15 16 17 X,Y=mgrid[-5:5:0.1,-5:5:0.1] 18 Z=sin(X2+Y2+1e-4)/(X2+Y2+1e-4) 19 imsave('imsave.png', Z, cmap=cm.hot )

imsave.png

SciPy: Cookbook/Matplotlib/converting_a_matrix_to_a_raster_image (last edited 2015-10-24 17:48:24 by anonymous)