如何在背景中使用图像创建Bokeh图?

2024-04-25 23:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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)

形象 enter image description here


Tags: fromimageimporturlsourcedfimgbokeh
1条回答
网友
1楼 · 发布于 2024-04-25 23:05:29

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

  • 在基于目录的应用程序中使用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运行

相关问题 更多 >

    热门问题