问题描述
我正在研究某种计算机视觉算法,我想展示一个numpy数组在每个步骤中如何变化.
I'm working on some computer vision algorithm and I'd like to show how a numpy array changes in each step.
现在有效的是,如果我在代码末尾有一个简单的imshow( array )
,则窗口将显示并显示最终图像.
What works now is that if I have a simple imshow( array )
at the end of my code, the window displays and shows the final image.
不过,我想做的是在每次迭代中更改图像时更新并显示imshow窗口.
However what I'd like to do is to update and display the imshow window as the image changes in each iteration.
例如,我想这样做:
import numpy as np
import matplotlib.pyplot as plt
import time
array = np.zeros( (100, 100), np.uint8 )
for i in xrange( 0, 100 ):
for j in xrange( 0, 50 ):
array[j, i] = 1
#_show_updated_window_briefly_
plt.imshow( array )
time.sleep(0.1)
问题在于这样一来,只有在完成整个计算后,Matplotlib窗口才会被激活.
The problem is that this way, the Matplotlib window doesn't get activated, only once the whole computation is finished.
我已经尝试了本机matplotlib和pyplot,但是结果是相同的.对于绘制命令,我发现了一个.ion()
开关,但是在这里似乎不起作用.
I've tried both native matplotlib and pyplot, but the results are the same. For plotting commands I found an .ion()
switch, but here it doesn't seem to work.
Q1.持续显示对numpy数组(实际上是uint8灰度图像)的更新的最佳方法是什么?
Q1. What is the best way to continuously display updates to a numpy array (actually a uint8 greyscale image)?
Q2.是否可以通过动画功能(例如动态图像示例)来实现?我想在循环中调用一个函数,因此我不知道如何使用动画函数来实现这一点.
Q2. Is it possible to do this with an animation function, like in the dynamic image example? I'd like to call a function inside a loop, thus I don't know how to achieve this with an animation function.
推荐答案
您不需要一直打imshow
.使用对象的set_data
方法要快得多:
You don't need to call imshow
all the time. It is much faster to use the object's set_data
method:
myobj = imshow(first_image)
for pixel in pixels:
addpixel(pixel)
myobj.set_data(segmentedimg)
draw()
draw()
应确保后端更新图像.
The draw()
should make sure that the backend updates the image.
更新:您的问题已被重大修改.在这种情况下,最好再问一个问题.这是解决第二个问题的方法:
UPDATE: your question was significantly modified. In such cases it is better to ask another question. Here is a way to deal with your second question:
Matplotlib的动画仅处理一个增加的维度(时间),因此您的双循环将不起作用.您需要将索引转换为单个索引.这是一个示例:
Matplotlib's animation only deals with one increasing dimension (time), so your double loop won't do. You need to convert your indices to a single index. Here is an example:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
nx = 150
ny = 50
fig = plt.figure()
data = np.zeros((nx, ny))
im = plt.imshow(data, cmap='gist_gray_r', vmin=0, vmax=1)
def init():
im.set_data(np.zeros((nx, ny)))
def animate(i):
xi = i // ny
yi = i % ny
data[xi, yi] = 1
im.set_data(data)
return im
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=nx * ny,
interval=50)
这篇关于如何交互更新matplotlib的imshow()窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!