Jupyter Lab 交互式图像显示:使用 HBox 布置小部件时出现问题

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

我的代码如下:

#%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])) => 参见 The figure is displayed twice
如何仅将图像显示在 HBox 中?
当我使用滑块改变值时,得到以下结果 => After changing value
1个回答

0

看起来 matplotlib 不能直接在 figure() 调用时绘制图形,但可以将其封装在一个 Output 小部件中(从 这里 获取):

output = widgets.Output()
with output:
  fig = plt.figure()

# fill figure with content here

display(HBox([slider, output]))

这样,情节就能正确地显示一次。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接