【问题标题】:Display array as raster image in python在python中将数组显示为光栅图像
【发布时间】:2011-04-22 15:00:41
【问题描述】:

我在 Python 中有一个 numpy 数组,我想在屏幕上将它显示为光栅图像。最简单的方法是什么?它不需要特别花哨或有一个漂亮的界面,我需要做的就是将数组的内容显示为灰度光栅图像。

我正在尝试使用 NumPy 将我的一些 IDL 代码转换为 Python,并且基本上正在寻找 IDL 中 tvtvscl 命令的替代品。

【问题讨论】:

    标签: python image image-processing numpy


    【解决方案1】:

    在pylab交互模式下使用ipython,你可以这样做:

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

    或者不在pylab模式下:

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

    或者没有 pylab 命名空间的东西:

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

    【讨论】:

      【解决方案2】:

      根据您的需要,matplotlib's imshowglumpy 可能是最佳选择。

      Matplotlib 更加灵活,但速度较慢(即使您做对了所有事情,matplotlib 中的动画也可能非常耗费资源。)。但是,您将拥有一个非常棒的功能齐全的绘图库。

      Glumpy 非常适合快速、基于 openGL 的 2D numpy 数组的显示和动画,但它的功能更加有限。不过,如果您需要为一系列图像制作动画或实时显示数据,那么它是比 matplotlib 更好的选择。

      使用 matplotlib(使用 pyplot API 代替 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()
      

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

      【讨论】:

      【解决方案3】:

      快速添加:对于使用 matplotlib 显示,如果您希望图像显示为“光栅”,即像素化而不平滑,那么您应该在 imshow 调用中包含选项 interpolation='nearest'。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        相关资源
        最近更新 更多