在散景图中显示 base64 图像

Display base64 image inside a bokeh figure

假设我有一个小的红色子弹 base64 图像:

im = ‘iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==’

为了在我的笔记本中显示它,我使用:

from IPython import display
display.HTML(f'<img src="data:image/png;base64,{im}" />')

现在我想在我的笔记本散景图中绘制这个 base64 图像。

我应该如何进行,例如,如果我想在散景图中随机绘制 5 im(见下图)。 ?

我认为你可以做两件事。设置 标记 的样式以满足您的目标,或根据需要使用图中的 image_url 加载图像 url。来自 Bokeh 的文档:图像的实际检索和加载发生在客户端 所以我认为您可能需要将 base64string 转换为图像并传递 URL。如果你能做到这一点,我会为我想到的 2 个解决方案生成下面的代码:

from bokeh.plotting import figure
from bokeh.io import output_file, show
from bokeh.layouts import row, column

import pandas as pd
import numpy as np
# generate random floating point values
from numpy.random import seed
from numpy.random import randint


# set number of random points
N=5
seed(1)
x_values = randint(0, 10, N)
y_values = randint(0, 10, N)

offset = 2
x_min = np.amin(x_values) - offset
x_max = np.amax(x_values) + offset
y_min = np.amin(y_values) - offset
y_max = np.amax(y_values) + offset


# Solution 1: style circle marker to achive what you want
p1 = figure(x_range=(x_min, x_max), y_range=(y_min, y_max))
p1.circle(x_values, y_values, color='red', size=30, alpha=0.8)
p1.xaxis.visible = False
p1.yaxis.visible = False
p1.xgrid.visible = False
p1.ygrid.visible = False


# Solution 2: using image_url
image_url = "https://upload.wikimedia.org/wikipedia/commons/0/02/Red_Circle%28small%29.svg"
p2 = figure(x_range=(x_min, x_max), y_range=(y_min, y_max))

for index in range(len(x_values)):
    p2.image_url(url=[image_url], x = x_values[index], y = y_values[index], anchor="center")

p2.xaxis.visible = False
p2.yaxis.visible = False
p2.xgrid.visible = False
p2.ygrid.visible = False

# Display the plot
output_file('example.html')
layout = row(p1,p2)
show(layout)

看看这个: bokeh.plotting.Figure.image_url

还有: https://docs.bokeh.org/en/latest/docs/reference/models/glyphs/image_url.html

内置标记: https://docs.bokeh.org/en/latest/docs/user_guide/plotting.html

如果你在 txt 文件中有那个 base64 字符串,比如 "image-base64-string.txt" 并且你想输出一个 'red-circle.png' 您可以使用的图像文件:

import base64
    with open("image-base64-string.txt", 'r') as base64_img :
        base64_img_bytes = base64_img.encode('utf-8')
    
        with open('red-circle.png', 'wb') as image_png:
            image_png.write(base64.decodebytes(base64_img_bytes))    

@DSgUY image_url完成工作谢谢你的想法!

from bokeh.plotting import figure, show, output_file
import base64
im = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
url = 'data:image/png;base64,'+im 
p = figure(x_range=(0,500), y_range=(0,500))
p.image_url( url=[url], x=300, y=300,w=100,h=100)
show(p)