【问题标题】:How to plot interactive draw-able image using matplotlib in Google Colab?如何在 Google Colab 中使用 matplotlib 绘制交互式可绘制图像?
【发布时间】:2019-08-14 21:17:46
【问题描述】:

我正在尝试绘制一个交互式图像,它可以让我在 Google Colab Notebook 的输出中绘制线条。我尝试使用下面的代码。它在我本地的 Jupyter Notebook 中运行良好,但在 Google colab 中无法运行。

任何人都可以提出任何解决方法吗?

也尝试添加%matplotlib inline,但显示的是静止图像。

from matplotlib.lines import Line2D
%pylab notebook 
%matplotlib inline
#This is needed for plot widgets

class Annotator(object):
    def __init__(self, axes):
        self.axes = axes

        self.xdata = []
        self.ydata = []
        self.xy    = []
        self.drawon = False

    def mouse_move(self, event):
        if not event.inaxes:
            return

        x, y = event.xdata, event.ydata
        if self.drawon:
            self.xdata.append(x)
            self.ydata.append(y)
            self.xy.append((int(x),int(y)))
            line = Line2D(self.xdata,self.ydata)
            line.set_color('r')
            self.axes.add_line(line)

            plt.draw()

    def mouse_release(self, event):
        # Erase x and y data for new line
        self.xdata = []
        self.ydata = []
        self.drawon = False

    def mouse_press(self, event):
        self.drawon = True


img = np.zeros((28,28,3),dtype='uint8')

fig, axes = plt.subplots(figsize=(3,3))
axes.imshow(img)
plt.axis("off")
plt.gray()
annotator = Annotator(axes)
plt.connect('motion_notify_event', annotator.mouse_move)
plt.connect('button_release_event', annotator.mouse_release)
plt.connect('button_press_event', annotator.mouse_press)

axes.plot()

plt.show()

我希望 Google Colab 中的输出是交互式的,就像我 PC 中的 Jupyter 笔记本一样,但输出仍然是图像,无法在其上绘制任何内容。

【问题讨论】:

  • 文档包含several interactive examples for Altair and plotly。 (不确定 matplotlib 需要什么。)
  • 我认为 Google Colab 不支持任何交互式后端(如 %matplotlib notebook 或 %matplotlib ipympl)。 Jupyter notebook 或 jupyterhub 可能更适合这种情况。
  • 谢谢@BobSmith,但我需要 Colab 中的交互式输出,我想这是不可能的。
  • 嗨@ImportanceOfBeingErnest,我想利用 Colab GPU 来修饰我的模型。如果 Jupyter notebook 或 jupyterhub 只能提供交互式后端。您能否建议我如何将 Colab 的训练模型与 Jupyter 笔记本连接以使用matplotlib

标签: matplotlib mouse draw interactive google-colaboratory


【解决方案1】:

首先,您必须使用 Google 云端硬盘中的目录挂载 colab。你可以试试:

fig = plt.figure()
fig.savefig("your_file_name.png")

from IPython.display import Image
Image("your_file_name.png")

【讨论】:

    猜你喜欢
    • 2021-01-18
    • 2021-04-08
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2012-02-26
    • 2022-06-13
    • 2017-04-17
    • 2016-05-08
    相关资源
    最近更新 更多