首页 > 解决方案 > 带文字的水印图片

问题描述

我正在尝试在绘图上添加水印图像,就像在这个答案中完成的那样,而且还在水印图像的底部添加一些文本。

我不能只将文本作为图像的一部分,因为它会不时变化。

img = mpimg.imread('/path/to/image.png')
imagebox = OffsetImage(img, alpha=0.5)
ao = AnchoredOffsetbox('lower left', pad=0, borderpad=1, child=imagebox)        
ax.add_artist(ao)

无法将另一个 Artist 添加到 AnchoredOffsetbox,因为只能有一个 child

有什么方法可以向该图像添加文本,或者我可以使用另一个容器吗?

谢谢!

标签: pythonmatplotlib

解决方案


文档中所述,如果您想要一个 中的多个孩子AnchoredOffsetbox,您可以选择使用容器框 ( VPacker, HPacker):

当需要多个孩子时,请使用其他 OffsetBox 类将它们括起来。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import (OffsetImage, TextArea, AnchoredOffsetbox, VPacker)


def create_watermark(imagePath, label, ax=None, alpha=0.5):
    if ax is None:
        ax = plt.gca()

    img = plt.imread(imagePath)
    imagebox = OffsetImage(img, alpha=alpha, zoom=0.2)
    textbox = TextArea(label, textprops=dict(alpha=alpha))
    packer = VPacker(children=[imagebox, textbox], mode='fixed', pad=0, sep=0, align='center')
    ao = AnchoredOffsetbox('lower left', pad=0, borderpad=1, child=packer)
    ax.add_artist(ao)


if __name__ == '__main__':
    fig, ax0 = plt.subplots()
    create_watermark('../lena.png', 'WATERMARK', ax=ax0)
    plt.show()

在此处输入图像描述


推荐阅读