2016-02-16 92 views
1

我有两种方法:显示图像的generate_window()和显示图像的窗口上点击的on_click()。他们是这样的:Pyplot:刷新imshow()窗口

def generate_panel(img): 
    plt.figure() 
    ax = plt.gca() 
    fig = plt.gcf() 
    implot = ax.imshow(img) 
    # When a colour is clicked on the image an event occurs 
    cid = fig.canvas.mpl_connect('button_press_event', onclick) 
    plt.show() 

def onclick(event): 
    if event.xdata != None and event.ydata != None: 
    # Change the contents of the plt window here 

在我希望能够改变在PLT窗口中显示的图像的代码的最后一行,但我似乎无法得到它的工作。我在不同的地方尝试过set_data()和draw(),但那没有奏效。有什么建议么?提前致谢。

回答

1

您还可以使用plt.ion() 启用交互模式,然后在您的修改应该工作后调用plt.draw()

注意:使用交互模式时,您必须在plt.show()上指定参数block=True以防止它立即关闭窗口。

你的榜样的这个修改后的版本应该上绘制每次鼠标点击一个圆圈:

from matplotlib import pyplot as plt 
import matplotlib.image as mpimg 
import numpy as np 


def generate_panel(img): 
    plt.figure() 
    ax = plt.gca() 
    fig = plt.gcf() 
    implot = ax.imshow(img) 
    # When a colour is clicked on the image an event occurs 
    cid = fig.canvas.mpl_connect('button_press_event', onclick) 
    plt.show(block=True) 


def onclick(event): 
    if event.xdata is not None and event.ydata is not None: 
     circle = plt.Circle((event.xdata, 
          event.ydata), 2, color='r') 
     fig = plt.gcf() 
     fig.gca().add_artist(circle) 
     plt.draw() 
     # Change the contents of the plt window here 


if __name__ == "__main__": 
    plt.ion() 
    img = np.ones((600, 800, 3)) 
    generate_panel(img) 
+0

你将如何实现这个的,即要在某个方法被调用来更新特定插曲matplotlib次要情节? – user3396592

+1

我不完全确定这一点,也许它取决于您使用的后端。 我相信matplotlib每次调用'draw()'函数时都会渲染整个画布。 您可以将不同的坐标轴/绘图放在不同的图形/腔体中,并用'fig_n.canvas.draw()'选择性地更新它们。 另一种方法是将所有子图放在同一个画布/图中并选择性地更新其数据,但始终显示整个画布(所有子图)。 – tmms