Python Matplotlib:在EPS中光栅化部分图形时去除黑色背景?

0 投票
1 回答
1965 浏览
提问于 2025-04-18 18:36

这个问题和另一个问题的评论有关。

在使用matplotlib和python时,我想把图像中的某个特定元素转化为栅格图像并保存为eps格式。问题是,当我保存为EPS格式时(而不是SVG或PDF),栅格化的元素后面会出现黑色背景。

把文件保存为PDF再转换成EPS似乎不是一个合理的解决办法,因为在pdf2ps和pdftops转换过程中会出现一些奇怪的问题,让人对边界框的理解感到非常...害怕(更糟糕的是,似乎不一致)。我现在的解决方法是通过一个复杂的过程先保存为svg格式,然后在Inkscape中导出,但这也不应该是必须的。

下面是重现这个问题所需的示例代码。你需要安装Matplotlib和Numpy。如果把文件保存为mpl-issue.py,可以通过以下命令运行:

python mpl-issue.py

#!/usr/bin/env python
# mpl-issue.py

import numpy as np
import matplotlib as mpl

# change backend to agg
# must be done prior to importing pyplot
mpl.use('agg')

import matplotlib.pyplot as plt

def transparencytest():
    # create a figure and some axes
    f = plt.figure()
    a = {
        'top': f.add_subplot(211),
        'bottom': f.add_subplot(212),
    }

    # create some test data
    # obviously different data on the subfigures
    # just for demonstration
    x = np.arange(100)
    y = np.random.rand(len(x))
    y_lower = y - 0.1
    y_upper = y + 0.1

    # a rasterized version with alpha
    a['top'].fill_between(x, y_lower, y_upper, facecolor='yellow', alpha=0.5, rasterized=True)

    # a rasterized whole axis, just for comparison
    a['bottom'].set_rasterized(True)
    a['bottom'].plot(x, y)

    # save the figure, with the rasterized part at 300 dpi
    f.savefig('testing.eps', dpi=300)
    f.savefig('testing.png', dpi=300)
    plt.close(f)

if __name__ == '__main__':
    print plt.get_backend()
    transparencytest()

生成的testing.png图像看起来是这样的: testing.png

testing.eps图像在转换为pdf版本和图形栅格化的png后看起来是这样的: testing.eps

栅格化元素后面的黑色背景是不应该出现的。我该如何在保存包含栅格化元素的eps图形时去掉这些黑色背景呢?

这个问题已经在其他一些mpl后端上测试过,所以看起来并不是agg特有的问题。我的系统是Mac OS X 10.9.4,Python 2.7.8是通过MacPorts安装的,Matplotlib版本是1.3.1。

1 个回答

0

这是一个已知的bug,现在已经修复了。

这个问题的原因是eps格式不支持透明度,而默认的栅格化背景颜色是(0, 0, 0, 0),也就是完全透明的黑色。

我也遇到过这个问题(https://github.com/matplotlib/matplotlib/issues/2473),现在已经在matplotlib 1.4.0版本中修复了,这个版本是昨晚发布的(https://github.com/matplotlib/matplotlib/pull/2479)。

撰写回答