且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何交互更新matplotlib的imshow()窗口?

更新时间:2023-10-24 23:22:58

您不需要一直打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)