【发布时间】:2018-05-17 19:23:20
【问题描述】:
我有一个可以在 pygame 下完美运行的快速动画程序,出于技术原因,我只需要使用 matplotlib 或其他广泛使用的模块来做同样的事情。
程序结构大致如下:
pygame.init()
SURF = pygame.display.set_mode((500, 500))
arr = pygame.surfarray.pixels2d(SURF) # a view for numpy, as a 2D array
while ok:
# modify some pixels of arr
pygame.display.flip()
pygame.quit()
我没有低级 matplotlib 经验,但我认为可以用 matplotlib 做类似的事情。换句话说:
如何分享图形的位图,修改部分像素,刷新屏幕?
这是一个最小的工作示例,它在我的计算机上每秒翻转 250 帧(超过屏幕......):
import pygame,numpy,time
pygame.init()
size=(400,400)
SURF = pygame.display.set_mode(size)
arr = pygame.surfarray.pixels2d(SURF) # buffer pour numpy
t0=time.clock()
for counter in range(1000):
arr[:]=numpy.random.randint(0,0xfffff,size)
pygame.display.flip()
pygame.quit()
print(counter/(time.clock()-t0))
编辑
我在答案中的指示尝试:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
def f(x, y):
return np.sin(x) + np.cos(y)
x = np.linspace(0, 2 * np.pi, 400)
y = np.linspace(0, 2 * np.pi, 400).reshape(-1, 1)
im = plt.imshow(f(x, y), animated=True)
count=0
t0=time.clock()+1
def updatefig(*args):
global x, y,count,t0
x += np.pi / 15.
y += np.pi / 20.
im.set_array(f(x, y))
if time.clock()<t0:
count+=1
else:
print (count)
count=0
t0=time.clock()+1
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=50, blit=True)
plt.show()
但这仅提供 20 fps....
【问题讨论】:
-
也许this 对你有帮助。
-
这不涉及编辑画布位图,但为了实时显示画布,答案是
plt.draw(); plt.pause(0.000001)。其中plt来自from matplotlib import pyplot as plt。可能与您的问题相关的帖子是:stackoverflow.com/questions/40126176/… -
Matplotlib 真的不是为高性能动画设计的。 “我只需要使用 matplotlib 或其他广泛使用的模块来做同样的事情。” 您能否更准确地说明您的要求?你认为什么是“广泛的模块”?您是否针对特定平台?
-
您将帧速率限制为每帧延迟 50 毫秒 (
interval=50)。也许减少它就足以获得您想要的性能...顺便说一句,time.clock()作为 unix 上的挂钟并不真正可靠,time.time()或timeit.default_timer可能是更好的选择,或者最近的time.perf_counter()蟒蛇
标签: python numpy matplotlib pygame