gpt4 book ai didi

python - Jupyter Lab 交互图像展示 : issue with widgets arrangements using HBox

转载 作者:行者123 更新时间:2023-12-05 07:16:51 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com