python - Jupyter Lab 交互图像展示 : issue with widgets a

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

我的代码如下:

#%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 中显示图像?

当我使用 slider 更改值时,我得到以下结果 => After changing value

最佳答案

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

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

# fill figure with content here

display(HBox([slider, output]))

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

关于python - Jupyter Lab 交互图像展示 : issue with widgets arrangements using HBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59022912/

相关文章:

hibernate - Spring JPA 审计因多个数据源而失败

visual-studio-code - VSCode 个人快捷方式在笔记本编辑器中不起作用

flutter - 将 mapEventToState 与传入流一起使用的最佳实践?

android - 无法再在 Android Studio 中运行单独的插桩测试

python-3.x - 如何在 Python 的 Microsoft O365 日历中将日期作为查

angular - 如果我重新分配一个存储 rxjs 订阅的变量,那会取消订阅吗?

reactjs - React 中的 forwardingRef 与回调 refs 有什么区别?

angular - ViewChild 与 Directive 获取 ViewContainerRe

python - 使用 Python Requests 在 postman 中做 post 请求

linkedin - 检索 Linkedin Video Post 的缩略图 (ugcPost AP