views:

64

answers:

2

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.

+3  A: 

Using ipython in the pylab interactive mode, you could do:

$ ipython pylab
In [1]: from pylab import *
In [2]: imshow(your_array)

edit: didn't import properly, made using ipython and pylab explicit

Thomas
Actually the from pylab import * happens automatically with 'ipython pylab', this is actually redundant.
Thomas
+4  A: 

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()
Joe Kington