python - 使用 Glumpy 将 NumPy 数组显示为不断更新的图像

标签 python opengl numpy plot glumpy

我有一个使用 NumPy 和 SciPy 在 Python 中运行的模拟模型,它会生成一个二维 NumPy 数组作为每次迭代的输出。我一直使用 matplotlib 和 imshow 函数将此输出显示为图像。然而,我发现了 Glumpy,在它的文档页面上它说:

多亏了 IPython shell,glumpy 可以在交互模式下运行,您可以在显示数组的内容更改时体验实时更新。

但是,我似乎无法弄清楚如何使用他们提供的示例来执行此操作。基本上我的模型作为一个函数运行,其中有一个很大的 for 循环来循环我正在运行的迭代次数。在 for 循环的每次迭代结束时,我想显示数组。目前我正在使用 matplotlib 将图像保存到 png 文件中,因为通过 matplotlib 在屏幕上显示它似乎卡住了 python 进程。

我确定有一种方法可以用 Glumpy 做到这一点,我只是不确定如何,而且我找不到任何有用的教程。

最佳答案

Glumpy 文档几乎不存在!下面是一个简单模拟的示例,将数组可视化与 glumpymatplotlib 进行比较:

import numpy as np
import glumpy
from OpenGL import GLUT as glut
from time import time
from matplotlib.pyplot import subplots,close
from matplotlib import cm

def randomwalk(dims=(256,256),n=3,sigma=10,alpha=0.95,seed=1):
    """ A simple random walk with memory """
    M = np.zeros(dims,dtype=np.float32)
    r,c = dims
    gen = np.random.RandomState(seed)
    pos = gen.rand(2,n)*((r,),(c,))
    old_delta = gen.randn(2,n)*sigma
    while 1:
        delta = (1.-alpha)*gen.randn(2,n)*sigma + alpha*old_delta
        pos += delta
        for ri,ci in pos.T:
            if not (0. <= ri < r) : ri = abs(ri % r)
            if not (0. <= ci < c) : ci = abs(ci % c)
            M[ri,ci] += 1
        old_delta = delta
        yield M

def mplrun(niter=1000):
    """ Visualise the simulation using matplotlib, using blit for 
    improved speed"""
    fig,ax = subplots(1,1)
    rw = randomwalk()
    im = ax.imshow(rw.next(),interpolation='nearest',cmap=cm.hot,animated=True)
    fig.canvas.draw()
    background = fig.canvas.copy_from_bbox(ax.bbox) # cache the background

    tic = time()
    for ii in xrange(niter):
        im.set_data(rw.next())          # update the image data
        fig.canvas.restore_region(background)   # restore background
        ax.draw_artist(im)          # redraw the image
        fig.canvas.blit(ax.bbox)        # redraw the axes rectangle

    close(fig)
    print "Matplotlib average FPS: %.2f" %(niter/(time()-tic))

def gprun(niter=1000):
    """ Visualise the same simulation using Glumpy """
    rw = randomwalk()
    M = rw.next()

    # create a glumpy figure
    fig = glumpy.figure((512,512))

    # the Image.data attribute is a referenced copy of M - when M
    # changes, the image data also gets updated
    im = glumpy.image.Image(M,colormap=glumpy.colormap.Hot)

    @fig.event
    def on_draw():
        """ called in the simulation loop, and also when the
        figure is resized """
        fig.clear()
        im.update()
        im.draw( x=0, y=0, z=0, width=fig.width, height=fig.height )

    tic = time()
    for ii in xrange(niter):
        M = rw.next()           # update the array          
        glut.glutMainLoopEvent()    # dispatch queued window events
        on_draw()           # update the image in the back buffer
        glut.glutSwapBuffers()      # swap the buffers so image is displayed

    fig.window.hide()
    print "Glumpy average FPS: %.2f" %(niter/(time()-tic))

if __name__ == "__main__":
    mplrun()
    gprun()

使用 matplotlibGTKAgg 作为我的后端,并使用 blit 来避免每次绘制背景,我可以达到大约 95 FPS。使用 Glumpy,我可以获得大约 250-300 FPS,即使我目前在我的笔记本电脑上的图形设置相当糟糕。话虽如此,Glumpy 开始工作有点麻烦,除非您正在处理巨大的矩阵,或者出于某种原因需要非常高的帧率,否则我会坚持使用 matplotlib blit

关于python - 使用 Glumpy 将 NumPy 数组显示为不断更新的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3942549/

相关文章:

Python - Pandas 删除 excel 中的特定行/列

python - 动态更新 mongodb

python - 如何使用特定的 dtype 填充现有的 numpy 数组

python - 如何使用 python 删除包含特定模式的列表的元素?

python - 在 CI 管道中部署 Dataflow

c++ - 在类中渲染 OpenGL 对象?

c++ - OpenGL:创建复杂且平滑的多边形

opengl - 权限被拒绝在Linux上运行我自己的程序?

python - 列切片和行切片之间哪个是哪个?

python - 将两个非线性模型拟合到数据