如何将文本边框与pyplot.Rectangle对齐?

2024-03-28 11:36:56 发布

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

我试图将一个带有边框的文本放在另一个边框的正上方(带有fill=Falsepyplot.Rectangle

代码如下:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

%matplotlib inline

FIGSIZE = (8, 8)
LINEWIDTH = 3
FONTSIZE = 12
X_MIN, Y_MIN = 68, 93
X_MAX, Y_MAX = 191, 380
WIDTH = X_MAX - X_MIN
HEIGHT = Y_MAX - Y_MIN
IMG_PATH = "data/PennFudanPed/PNGImages/FudanPed00002.png"

img = np.array(Image.open(IMG_PATH))
fig, ax = plt.subplots(figsize=FIGSIZE)
ax.imshow(img, aspect="equal")
ax.add_patch(plt.Rectangle(
    (X_MIN, Y_MIN), 
    WIDTH, 
    HEIGHT,
    fill=False,
    edgecolor="red",
    linewidth=LINEWIDTH
))
ax.text(
    X_MIN, 
    Y_MIN,
    "Walking person",
    bbox=dict(facecolor="blue", edgecolor='none', alpha=0.5),
    fontsize=FONTSIZE,
    color="white",
    horizontalalignment='left',
    verticalalignment='bottom',
)
plt.axis('off')
plt.tight_layout()

不幸的是,我无法使它与主边界框完全对齐(垂直和水平)。我可以手动调整位置,但如果我更改了FIGSIZE、LINEWIDTH或FONTSIZE,文本边界框将不再对齐

结果是:

enter image description here

这张照片是here拍摄的

如何使文本的边框与矩形对齐


Tags: 文本importfalseaspltaxminfill