【问题标题】:How can I add a .png watermark to a graph made on matplotlib?如何在 matplotlib 上制作的图形中添加 .png 水印?
【发布时间】:2023-02-01 14:45:07
【问题描述】:

我想使用 .png 图像在使用 matplotlib 的图表上添加水印(但在绘制的线/点/条下)。在不破坏过程中的图表的情况下,我无法做到这一点。

以下代码在 matplotlib 中制作了一个简单的图表:

import matplotlib.pyplot as plt

def MakePlotWithWatermark():
    fig, ax = plt.subplots(figsize = (10, 5))
    ax.grid(True, which='both', axis='both', linestyle='--', linewidth=0.5)
    ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], marker='o', color = "Blue")
    plt.close()
    return fig

这按预期工作,将其命名为 output。

但是,我想在图表中添加水印。为了举例,我将使用一张笑脸图片。我修改我的功能如下:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg

def MakePlotWithWatermark():
    fig, ax = plt.subplots(figsize = (10, 5))
    ax.grid(True, which='both', axis='both', linestyle='--', linewidth=0.5)
    ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], marker='o', color = "Blue")
    
    PathToWatermark = "SmileyWatermark.png"
    img = mpimg.imread(PathToWatermark)
    ax.imshow(img, alpha=0.1)
    
    plt.close()
    return fig

现在,the resulting chart 没有正确显示数据。

如何在不更改情节的任何其他内容的情况下添加水印?

我已经尝试了来自this post 的答案:这是resulting output. 如果可能的话,我希望整个水印都可见,并且尽可能靠近绘图的中心。我也想保持配色方案相同。

我也试过 this reply 和 this output 的答案。我怀疑调整我们的水印大小以匹配绘图区域的大小和形状会得到一个完美的解决方案

【问题讨论】:

  • 它取得了一些进展。但是,图像现在太大并且不完全可见。我还需要面部颜色保持不变,配色方案在这里很重要。我似乎无法在此评论中附加图片。我将编辑初始帖子以显示结果。

标签: python image matplotlib


【解决方案1】:

尝试这个:

import requests
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
from matplotlib.offsetbox import ( OffsetImage, AnchoredOffsetbox, AnnotationBbox)


def MakePlotWithWatermark():
    
    img_rep = requests.get('https://i.ibb.co/6YLhH1N/Untitled-1.jpg')
    img = Image.open(BytesIO(img_rep.content))
    
    fig, ax = plt.subplots(figsize = (10, 5))
    ax.grid(True, which='both', axis='both', linestyle='--', linewidth=0.5)
    ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25], marker='o', color = "Blue")
    
    imagebox = OffsetImage(img, zoom=0.5, alpha=0.2)
    imagebox.image.axes = ax
    
    #ao = AnchoredOffsetbox(4, pad=0.01, borderpad=0, child=imagebox)  # method 1
    ao = AnnotationBbox(imagebox, (0.5, 0.5), xycoords='axes fraction', bboxprops={'lw':0})  # method 2
    ao.patch.set_alpha(0)
    ax.add_artist(ao)
    
    plt.close()
    return fig

MakePlotWithWatermark()

【讨论】:

  • 这非常接近。然而,它略微扩大了图像边距,这是一个问题。有没有办法检测绘图区域的大小,并在将图像添加到绘图之前自动将图像重新缩放到相同的大小?我已经编辑了显示输出的原始帖子。
  • 你想要图像在中心还是什么??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
相关资源
最近更新 更多