python数组展示_python – 使用Glumpy显示NumPy数组不断更新图像

本文对比了使用matplotlib和Glumpy库显示NumPy数组的实时更新图像。通过一个简单的随机漫步模拟,展示两者在性能上的差异。在测试中,matplotlib借助blit实现约95 FPS,而Glumpy能达到250-300 FPS。尽管Glumpy性能更优,但其使用相对复杂,适合处理大型矩阵或高帧率需求的场景。
摘要由CSDN通过智能技术生成

Glumpy文档是相当不存在的!这是一个简单模拟的例子,将数组可视化与glumpy与matplotlib进行比较:

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

使用matplotlib和GTKAgg作为我的后端并使用blit来避免每次绘制背景,我可以达到大约95 FPS.使用Glumpy我得到大约250-300 FPS,即使我目前在我的笔记本电脑上设置了相当糟糕的图形设置.话虽如此,Glumpy开始工作有点繁琐,除非你处理巨大的矩阵,或者你需要一个非常高的帧率,无论出于何种原因,我都会坚持使用matplotlib和blit.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值