Altair - 在背景图像上绘图

问题描述 投票:0回答:1

我想显示图像并在其上绘制标记。但是,图像似乎与轴没有很好地对齐,导致标记位于错误的位置。这是我的代码:

import altair as alt
import pandas as pd
from PIL import Image
import numpy as np
from io import BytesIO
import base64


def toBase64(np_img):
    # convert numpy image to base64 string
    with BytesIO() as buffer:
        Image.fromarray(np_img).save(buffer, 'png')
        img_str = base64.encodebytes(buffer.getvalue()).decode('utf-8')
    return f"data:image/png;base64,{img_str}"


h,w = 250,410 
im0 = np.zeros((h,w,3), dtype=np.uint8)
tmp = pd.DataFrame([
    {"x": w//2, "y": h//2, "img": toBase64(im0)}
])
backgrd = alt.Chart(tmp).mark_image(
    width=w,
    height=h
).encode(x='x', y='y', url='img')
b0_df = pd.DataFrame({'x': [0,0,w,w], 'y': [0,h,0,h]})
b0 = alt.Chart(b0_df).mark_circle(size=30, color='red').encode(x='x', y='y').properties(width=w, height=h)
(backgrd+b0)

结果如下所示:

标记绘制正确,但图像不正确。另外,图像似乎被拉伸了一些。在绘图上,我可以设置

xref
yref
以使图像比例与轴比例相同,如何在 Altair 上做到这一点?

python altair vega-lite python-interactive
1个回答
0
投票

您可以尝试调整轴限制以确保它们不会超过x/y最大值:

# top of your code
# ...

d = b0_df.max().add(1).to_dict()

backgrd.encoding.x.scale = alt.Scale(domain=[0, d["x"]])
b0.encoding.x.scale = alt.Scale(domain=[0, d["x"]])

backgrd.encoding.y.scale = alt.Scale(domain=[0, d["y"]])
b0.encoding.y.scale = alt.Scale(domain=[0, d["y"]])

(backgrd+b0)

输出:

© www.soinside.com 2019 - 2024. All rights reserved.