如何在背景中创建带有图像的散景图?

How to create Bokeh plots with image in background?

我想用 Bokeh 创建一个圆图,背景是一张图片,请参见下面的代码。我无法弄清楚为什么不显示图像。是我的代码有问题,还是我使用的方法不对?

import pandas as pd
import cv2

from bokeh.models import ImageURL, ColumnDataSource
from bokeh.plotting import figure
from bokeh.models.ranges import DataRange1d
from bokeh.io import show

df = pd.DataFrame({'Time': [2586, 2836, 2986, 3269, 3702],
                   'X': [120, 210, 80, 98, 40],
                   'Y': [230, 40, 33, 122, 10],
                   'User': ['u1', 'u1', 'u2', 'u2', 'u2']})

source = ColumnDataSource(data=dict(time=df['Time'], x=df['X'], y=df['Y'], user=df['User']))

#read image
img_url = 'tree.jpg'
image=cv2.imread(img_url)

sx = image.shape[1]
sy = image.shape[0]
x_range = DataRange1d(start = 0, end = sx, bounds = (0, sx), range_padding = 5, range_padding_units = 'percent')
y_range = DataRange1d(start = sy, end = 0, bounds = (0, sy), range_padding = 5, range_padding_units = 'percent')
pw = 600
ph = int(pw * sy / sx)

# Create the figure: p
p = figure(x_axis_label='X', y_axis_label='Y', plot_width = pw, plot_height = ph, 
           x_range=x_range, y_range=y_range, match_aspect=True)
p.image_url(url=[img_url], x = 0, y = 0, w = sx, h = sy, anchor="top_right")
p.circle(x='x', y='y', source=source, size=10, color='blue', fill_color='white', alpha=0.8)

show(p)

图片

img_url 需要是结果页面能够访问的正确 URL。文件的本地文件系统路径不是 URL。不幸的是,如果不使用某种网络服务器,您不能将 image_url 用于本地文件,因为出于安全原因,网页无法访问本地文件。我能想到的两个可行方案:

  • bokeh serve 与基于目录的应用程序一起使用。它将允许您通过 static 目录
  • 提供任意文件
  • 不要使用 image_url,请使用 image_rgba。您已经阅读了整张图片,因此您可以将其作为数据提供,而不是作为 URL

如果您无法使 image_url 工作,请尝试使用其锚点并确保 url 参数以目录名称开头。我可以通过创建一个名为 test_app:

的目录来显示图像
test_app
├── main.py
└── static
    └── tree.png

其中 main.py 只有

from bokeh.io import curdoc
from bokeh.plotting import figure

p = figure()
p.image_url(url=['/test_app/static/tree.png'],
            x=[0], y=[0], w=[1], h=[1], anchor="bottom_left")

curdoc().add_root(p)

应该是运行,因为bokeh serve test_app