【问题标题】:Jupyter Lab interactive image display : issue with widgets arrangements using HBoxJupyter Lab 交互式图像显示:使用 HBox 的小部件排列问题
【发布时间】:2020-03-20 05:14:19
【问题描述】:

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

我的代码如下:

#%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

【问题讨论】:

    标签: python matplotlib jupyter-lab ipywidgets


    【解决方案1】:

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

    output = widgets.Output()
    with output:
      fig = plt.figure()
    
    # fill figure with content here
    
    display(HBox([slider, output]))
    

    这样,图就正确显示了一次。

    【讨论】:

      猜你喜欢
      • 2019-03-06
      • 2021-01-18
      • 2019-12-15
      • 2021-08-01
      • 2017-11-03
      • 1970-01-01
      • 2019-11-24
      • 2017-01-13
      相关资源
      最近更新 更多