python - 带文字的水印图片
问题描述
我正在尝试在绘图上添加水印图像,就像在这个答案中完成的那样,而且还在水印图像的底部添加一些文本。
我不能只将文本作为图像的一部分,因为它会不时变化。
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。
有什么方法可以向该图像添加文本,或者我可以使用另一个容器吗?
谢谢!
解决方案
如文档中所述,如果您想要一个 中的多个孩子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()
推荐阅读
- python - 如何在一台机器上运行 gRPC 客户端,在另一台机器上运行 gRPC 服务器?
- django - 序列化具有多对多字段的嵌套 Django 模型
- python - 如何提取 DataCompy 比较结果?
- python - 我们如何将模型设置为 django 中的 default=0 或 default=null
- spring - 您应该如何对 HATEOAS 和返回 HATEOAS 的控制器进行单元测试?
- uipath - Uipath如何从不同的excel表中添加数据
- python - 如何按键值正确排序字典?
- python-3.x - 我想清理一个脚本,它会在 X 分钟不活动后自动锁定并关闭我的屏幕
- swift - .isComplicationEnabled 是否在模拟器中工作?
- jquery - 需要帮助来提高使用 canvas2image javascript 的分辨率(应该很容易.. 但我很新)