【问题标题】:Matplotlib imshow with EPSMatplotlib imshow 与 EPS
【发布时间】:2015-07-30 10:18:38
【问题描述】:

有没有办法将PIL 与 matplotlib 结合使用来放置 EPS 或 SVG(或任何可缩放矢量格式)的徽标,以便将徽标放置在图形上并将最终文件输出为 EPS。现在我得到一个渲染得非常糟糕的图形,因为有一个 .png 文件试图转换为 EPS 格式,目标是将图像保存为 .eps.svg

我认为这可能是由于后端的限制,我愿意更改我使用的那个。

这是行不通的:

    ax1.set_axis_bgcolor('#fafafa')
    
    img = image.imread('./static/images/logo.png')
    image_axis = fig.add_axes(ax1.get_position())
    image_axis.patch.set_visible(False)
    image_axis.yaxis.set_visible(False)
    image_axis.xaxis.set_visible(False)
    image_axis.set_xlim(0,19.995)
    image_axis.set_ylim(0,11.25)

    image_axis.imshow(img, extent=(11.79705,18.99525,.238125,1.313625), zorder=-1, alpha=0.15) #need to keep a 5.023 x by y ratio (.4 x .079)

    fig.savefig('static/images/graphs/'+filename+'.eps', format='eps', bbox_inches='tight')

有什么更新吗?

【问题讨论】:

  • 你试过了吗? The docs 暗示如果传递给 imshow 的图像是非 png 的,matplotlib 将依赖 PIL,它应该能够处理 eps (docs)。我没有任何 eps 文件可供测试,但可能会在明天尝试。

标签: python svg matplotlib eps


【解决方案1】:

这是一个老问题,但对于想要这样做的当前和未来访问者来说,值得回答。

有一种方法可以加载 SVG 文件并将它们转换为 Path 对象,在 svgpath2mpl 包中实现。从项目页面:

SVG 中的路径由包含d="(path data)" 属性的“路径”元素定义,该属性包含移动到、直线、曲线(三次和二次贝塞尔曲线)、弧线和关闭路径指令。 Matplotlib 实际上原生支持所有这些指令,但不提供解析器或完全兼容的 API。

见于Matplotlib custom marker/symbol

【讨论】:

    【解决方案2】:

    在这种情况下,我通常会通过以下方式获得更好的渲染:

    from PIL import Image
    
    logo = Image.open('icons\logo.png')
    # TODO define bbox as a matplotlib.transforms.Bbox
    image_axis.imshow(logo, clip_box=bbox, aspect='equal',
       origin='lower', interpolation='nearest')
    

    (Matplotlib 1.4.2,如果您使用旧版本玩 interpolationorigin 选项可能会有所帮助)

    【讨论】:

    • 这是否适用于矢量图形 - 而不是 pngs?
    • PIL 可以处理 .eps 文件 pillow.readthedocs.org/en/latest/handbook/… 它们将被光栅化,但您可以控制点的数量(见链接)
    • 目标是将图形保存为 eps 或其他可缩放矢量图形,包括徽标。
    • 好的。使用此代码,您可以将图形保存为 pdf(也可能是 eps,未经测试),其中包含徽标 - 但它将作为光栅图像嵌入。
    【解决方案3】:

    我删除了我的代码 sn-p,因为它没有用。

    在 Matplotlib 中无法使用原生 SVG 作为图像。 Matplotlib 本身仅支持 png,然后回退到也不支持 svg 的 Pillow,请参阅 http://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html 或 matplotlib 图像文档。

    Pillow 支持 eps,这样就可以了! (我不确定 matplotlib 会在内部做什么)

    我是这样使用它的:

    # Pillow must be there
    import matplotlib.image as mpimg
    
    def Save_svg(fig):
        # expects a matplotlib figure
        # And puts a logo into a frameless new axes
        imagefile = 'logo.eps'
        svgfile   = 'output.svg'
        logoax    = [0.265, 0.125, 0.3, 0.3]
        img=mpimg.imread(imagefile)
        #
        newax = fig.add_axes(logoax, anchor='SW', zorder=100)
        newax.imshow(img)
        newax.axis('off')
        #
        fig.savefig(svgfile,dpi=300)
    

    【讨论】:

    • 您的示例嵌入了 jpg 徽标 - 我认为 OP 想要嵌入 eps/svg。我认为关键是他们希望始终保持矢量图形。
    • @JRichardSnape 没错——我们的目标是输出 SVG/EPS。我还没有解决这个问题,但如果我解决了会更新。
    • 我最近解决了,所以我完全更新了上面的答案
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多