Pyplot:刷新imshow()风

2024-04-25 12:32:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个方法:generate_window()用于显示图像,on_click()用于响应单击显示图像的窗口。它们看起来像这样:

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(),但都没用。有什么建议吗?提前谢谢。在


Tags: the方法图像noneeventimgondef
1条回答
网友
1楼 · 发布于 2024-04-25 12:32:13

您还必须使用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)

相关问题 更多 >