Display array as raster image in python

2020-05-19 08:22发布

问题:

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.

回答1:

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


回答2:

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

$ ipython pylab
In [1]: imshow(your_array)

or not in pylab mode:

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

or without the pylab namespace thing:

$ ipython
In [1]: import matplotlib.pyplot as pyplot
In [2]: pyplot.imshow(your_array)
In [3]: pyplot.show()


回答3:

Quick addition: for displaying with matplotlib, if you want the image to appear "raster", i.e., pixelized without smoothing, then you should include the option interpolation='nearest' in the call to imshow.