【问题标题】:Slow matplotlib and ipywidgets image refresh缓慢的 matplotlib 和 ipywidgets 图像刷新
【发布时间】:2020-12-12 11:05:51
【问题描述】:

我正在尝试使用 plt.show() 和 ipywidgets interact() 函数滚动浏览一些磁共振切片。通过缓慢移动滑块我发现没有问题,但是在更快地通过切片时发现了一个重要的延迟。

下面是我正在使用的代码。

def dicom_animation(x, volume):
    fig = plt.figure(figsize=(8,8))
    plt.imshow(volume['slices'][x]['pixel_array'], cmap=plt.cm.gray)


interact(dicom_animation, volume = fixed(a), x=IntSlider(round(len(a['slices'])/2,0), 0, (len(a['slices'])-1), layout=Layout(width='500px')))

this 就是结果。

我有什么办法可以让滑动速度更快一点,而不会出现这个重要的延迟?

【问题讨论】:

  • 我没有看到您的代码有任何延迟
  • plt图片刷新滞后于光标滑动

标签: python matplotlib jupyter-notebook ipywidgets


【解决方案1】:

重新制作图形和调用plt.imshow 都是相当昂贵的操作,这正是减慢速度的原因。相反,您需要使用交互式 matplotlib 后端,然后使用 set_data 之类的方法。

安装ipympl

ipympl 是 matplotlbi 的交互式后端,可在 jupyter nobteook 和 jupyterlab 中使用。它有一个很好的示例笔记本,在这里解释了如何与其他小部件进行交互:https://github.com/matplotlib/ipympl/blob/0.6.1/examples/ipympl.ipynb

对于 JupyterLab 3+ 来说,安装它要容易得多所以:

pip install --upgrade jupyterlab ipympl

手动创建滑块

虽然interact 很方便,但它往往不能很好地与 ipympl 配合使用,因为它希望在每次滑块更改时完全重新生成输出。

%matplotlib ipympl

# the rest of your setup code

fig, ax = plt.figure()
img = ax.imshow(volume['slices'][x]['pixel_array'], cmap=plt.cm.gray)

def update_plot(change):
    img.set_data(volume['slices'][change['new']['pixel_array']
    fig.canvas.draw_idle()

x_slider = IntSlider(round(len(a['slices'])/2,0), 0, (len(a['slices'])-1)
x_slider.observe(update_plot, names='value')

使用 mpl 交互

手动设置滑块可能很麻烦。所以我写了一个库,可以很容易地使用小部件来控制交互式绘图。它处理创建滑块并执行所有正确的操作,例如为您使用 set_data。如果您不在 jupyter 笔记本中,它还将使用 matplotlib 滑块,因此它更便携。

在您的情况下,您会对imshow example 感兴趣 或者根据您的数据结构,您也可以使用hyperslicer

你的例子是:

%matplotlib ipympl

import mpl_interactions.ipyplot as iplt
# other setup stuff
volume = a

def f(x):
    return volume['slices'][x]['pixel_array']

fig, ax = plt.subplots()
controls = iplt.imshow(f, cmap=plt.cm.gray, x = np.arange(0, len(a)-1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2012-08-02
    • 2021-08-08
    相关资源
    最近更新 更多