Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display array as raster image in python

Tags:

I've got a numpy array in Python and I'd like to display it on-screen as a raster image. What is the simplest way to do this? It doesn't need to be particularly fancy or have a nice interface, all I need to do is to display the contents of the array as a greyscale raster image.

I'm trying to transition some of my IDL code to Python with NumPy and am basically looking for a replacement for the tv and tvscl commands in IDL.

like image 810
robintw Avatar asked Oct 07 '10 22:10

robintw


1 Answers

Depending on your needs, either matplotlib's imshow or glumpy are probably the best options.

Matplotlib is infinitely more flexible, but slower (animations in matplotlib can be suprisingly resource intensive even when you do everything right.). However, you'll have a really wonderful, full-featured plotting library at your disposal.

Glumpy is perfectly suited for the quick, openGL based display and animation of a 2D numpy array, but is much more limited in what it does. If you need to animate a series of images or display data in realtime, it's a far better option than matplotlib, though.

Using matplotlib (using the pyplot API instead of pylab):

import matplotlib.pyplot as plt import numpy as np  # Generate some data... x, y = np.meshgrid(np.linspace(-2,2,200), np.linspace(-2,2,200)) x, y = x - x.mean(), y - y.mean() z = x * np.exp(-x**2 - y**2)  # Plot the grid plt.imshow(z) plt.gray() plt.show() 

Using glumpy:

import glumpy import numpy as np  # Generate some data... x, y = np.meshgrid(np.linspace(-2,2,200), np.linspace(-2,2,200)) x, y = x - x.mean(), y - y.mean() z = x * np.exp(-x**2 - y**2)  window = glumpy.Window(512, 512) im = glumpy.Image(z.astype(np.float32), cmap=glumpy.colormap.Grey)  @window.event def on_draw():     im.blit(0, 0, window.width, window.height) window.mainloop() 
like image 129
Joe Kington Avatar answered Oct 30 '22 12:10

Joe Kington