Jupyter Lab交互式图像显示:使用HBox进行小部件排列时出现问题

时间:2019-11-24 22:07:48

标签: python matplotlib jupyter-lab ipywidgets

我正在尝试使用滑块交互式地更改图像的内容(例如,应用具有不同值的阈值操作)。

我的代码如下:

#%matplotlib ipympl
%matplotlib widget
import matplotlib.pyplot as plt

import cv2
import numpy as np

import ipywidgets as widgets
from ipywidgets import HBox, IntSlider
from IPython.display import Image

def update_lines(change):
    ret,thresh2 = cv2.threshold(img_gray,change.new,255,cv2.THRESH_BINARY)
    plt.imshow(thresh2)
    fig.canvas.flush_events()

image = cv2.imread("Untitled.jpg")
img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret,thresh2 = cv2.threshold(img_gray,30,255,cv2.THRESH_BINARY)

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

slider = IntSlider(
    orientation='vertical',
    step=1,
    value=127,
    min=0,
    max=255
)

display(HBox([slider, fig.canvas]))

slider.observe(update_lines, names='value')

执行代码时,我有一个意外的行为:该图形显示两次,第一次执行fig = plt.figure(),第二次执行display(HBox([slider, fig.canvas])) =>参见{{3} }。

如何仅将图像显示在HBox中?

当我使用滑块更改值时,得到以下结果=> The figure is displayed twice

2 个答案:

答案 0 :(得分:0)

我不知道如何解决matplotlib领域中的问题,但是如果您愿意考虑其他方法,请考虑使用jp_doodle交互式小部件中提供的“图像流”功能。

请参阅“图像流演示笔记本”:

https://github.com/AaronWatters/jp_doodle/blob/master/notebooks/misc/image%20streaming%20demo.ipynb

您可以通过单击活页夹链接尝试使用活页夹

https://mybinder.org/v2/gh/AaronWatters/jp_doodle/master

从主页上

https://github.com/AaronWatters/jp_doodle

该小部件以常规方式嵌入。

答案 1 :(得分:0)

似乎无法直接说服matplotlib在::visit调用中绘制图形,但是可以将其封装在figure()小部件中(取自here):

Output

这样,绘图就可以正确显示一次。