如何使用 python 在交互式破折号中显示本地图像

How to show a local image in an interactive dash with python

所以我正在研究 Dash Plotly。该网页应该有一个文本框和一个按钮。这个想法是,当我写一个图像名称然后 select 按钮时,它将显示本地目录中的图像。

我试图将整个作品分成两部分。

首先,我有这段代码可以显示您在文本框中输入的内容并单击按钮。代码:

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import os 
from PIL import Image
import numpy as np
import plotly.express as px

os.chdir(os.path.dirname(os.path.abspath(__file__)))

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(
    [
        html.I("Try typing the image name in input and observe it"),
        html.Br(),
        dcc.Input(id="input", type="text", placeholder=""),
        html.Div(id="output"),
    ]
)


@app.callback(
    Output("output", "children"),
    Input("input", "value")
)
def update_output(input):
    return u'Input {}'.format(input)


if __name__ == "__main__":
    app.run_server(debug=True)

接下来,我有这段代码,当 运行 在本地时,只显示网页中的图像。要点:python 文件和图像位于同一本地目录中。代码:

import os 

from PIL import Image
import numpy as np
import plotly.express as px

# Change working dir to current running script dir:
print('[change directory]')
os.chdir(os.path.dirname(os.path.abspath(__file__)))

def test():
    # load the image
    img = np.array(Image.open('img name.tiff'))

    fig = px.imshow(img, color_continuous_scale='gray')
    fig.update_layout(coloraxis_showscale=False)
    fig.update_xaxes(showticklabels=False)
    fig.update_yaxes(showticklabels=False)
    fig.show()

test()

现在,我需要一种方法来添加这两个代码,以便当我在文本框中写入 'img name.tiff' 并在按钮中写入 select 时,它会显示网页中的图片。

我是 Dash 和 Plotly 的新手。我不知道该怎么做。我试图研究它,但找不到任何有用的东西。有人可以帮忙吗?

您可以将回调更改为如下内容:

@app.callback(Output("output", "children"), Input("input", "value"))
def update_output(input):
    if not input:
        raise PreventUpdate

    try:
        img = np.array(Image.open(f"assets/{input}"))
    except OSError:
        raise PreventUpdate

    fig = px.imshow(img, color_continuous_scale="gray")
    fig.update_layout(coloraxis_showscale=False)
    fig.update_xaxes(showticklabels=False)
    fig.update_yaxes(showticklabels=False)

    return dcc.Graph(figure=fig)

如果没有输入值或者无法打开用户指定路径的图片,我们使用PreventUpdate:

In certain situations, you don't want to update the callback output. You can achieve this by raising a PreventUpdate exception in the callback function.

注意:此示例假设图像存储在 assets 文件夹中。

更新:使用按钮实现

@app.callback(
    Output("output", "children"),
    Input("input", "value"),
    Input("show-image", "n_clicks"),
    prevent_initial_call=True,
)
def update_output(input, n_clicks):
    if not input:
        raise PreventUpdate

    ctx = dash.callback_context
    if ctx.triggered[0]["prop_id"].split(".")[0] != "show-image":
        raise PreventUpdate

    try:
        img = np.array(Image.open(f"assets/{input}"))
    except OSError:
        raise PreventUpdate

    fig = px.imshow(img, color_continuous_scale="gray")
    fig.update_layout(coloraxis_showscale=False)
    fig.update_xaxes(showticklabels=False)
    fig.update_yaxes(showticklabels=False)

    return dcc.Graph(figure=fig)

在前面关于查找可以打开的图像的示例中,回调 returns 带有图像的图形。如果您想推迟显示图像直到单击按钮,您可以向布局添加一个按钮

html.Button("Show Image", id="show-image", n_clicks=0)

并使用 callback_context 确定哪个 Input 触发了按钮。如果此输入的 id 等于 "show-input"(我们按钮的 id),我们将显示图形和图像。