更新函数中的matplotlib映像 [英] Update matplotlib image in a function
问题描述
我有一个处理图像的循环,我希望在第100次迭代(例如)中使用matplotlib在单个输出窗口中显示图像.因此,我正在尝试编写一个函数,该函数将以numpy张量作为输入并显示相应的图像.
I've got a loop that's processing images and I want, on every 100th iteration (say) to display the image in a single output window using matplotlib. So I'm trying to write a function which will take a numpy tensor as input and display the corresponding image.
这是我所无法使用的:
def display(image):
global im
# If im has been initialized, update it with the current image; otherwise initialize im and update with current image.
try:
im
im.set_array(image)
plt.draw()
except NameError:
im = plt.imshow(image, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)
plt.show(block=False)
plt.draw()
我一开始试图通过 FuncAnimation 传递它,但这似乎旨在让动画调用一个函数来执行更新,而不是在 matplotlib 上调用函数来显示结果.
I was trying to pass it through FuncAnimation at first, but that seems designed to have the animation call a function to do the update, rather than having a function call on matplotlib to display the result.
上面的代码打开了一个窗口,但它似乎没有更新.任何人都可以在这里指出正确的方向吗?
The code above opens a window but it doesn't seem to update. Can anyone point me in the right direction here?
非常感谢,
Justin
推荐答案
也许你可以使用以下组合:
Maybe you can use a combination of:
第一个将重新绘制您的图形,而第二个将调用 GUI 事件循环来更新图形.
The first one will re-draw your figure, while the second one will call the GUI event loop to update the figure.
您也不必一直调用imshow,只需在"im"对象上调用"set_data"方法就足够了.这样的事情应该可以工作:
Also you don't need to call imshow all the times, it's sufficient to call the "set_data" method on your "im" object. Something like that should work:
import matplotlib.pyplot as plt
import numpy
fig,ax = plt.subplots(1,1)
image = numpy.array([[1,1,1], [2,2,2], [3,3,3]])
im = ax.imshow(image)
while True:
image = numpy.multiply(1.1, image)
im.set_data(image)
fig.canvas.draw_idle()
plt.pause(1)
这是改编自 这个答案.希望有帮助.
This was adapted from this answer. Hope it helps.
这篇关于更新函数中的matplotlib映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!