【问题标题】:matplotlib show many images in single pdf pagematplotlib 在单个 pdf 页面中显示许多图像
【发布时间】:2015-06-05 14:03:36
【问题描述】:

给定一个未知大小的图像作为输入,以下python 脚本在单个pdf 页面中显示它 8 次:

pdf = PdfPages( './test.pdf' )
gs = gridspec.GridSpec(2, 4)

ax1 = plt.subplot(gs[0])
ax1.imshow( _img )

ax2 = plt.subplot(gs[1])
ax2.imshow( _img )

ax3 = plt.subplot(gs[2])
ax3.imshow( _img )

# so on so forth...

ax8 = plt.subplot(gs[7])
ax8.imshow( _img )

pdf.savefig()
pdf.close()

输入图像可以有不同的大小(先验未知)。我尝试使用函数gs.update(wspace=xxx, hspace=xxx) 来更改图像之间的间距,希望matplotlib 会自动调整图像大小并重新分配图像以尽可能少地留白。但是,正如您在下面看到的,它并没有像我预期的那样工作。

有没有更好的方法来实现以下目标?

  1. 尽可能以最大分辨率保存图像
  2. 尽可能少的空白

理想情况下,我希望这 8 张图片完全符合 pdf 的页面大小(需要最少的边距)。

【问题讨论】:

  • 我的回答能解决你的问题吗?
  • @hitzg - 是的!我一直在等待更多反馈,但后来完全忘记了接受。对不起!

标签: python image pdf matplotlib


【解决方案1】:

您走在正确的道路上:hspacewspace 控制图像之间的空间。您也可以使用topbottomleftright 来控制图形上的边距:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.image as mimage
from matplotlib.backends.backend_pdf import PdfPages

_img = mimage.imread('test.jpg')

pdf = PdfPages( 'test.pdf' )
gs = gridspec.GridSpec(2, 4, top=1., bottom=0., right=1., left=0., hspace=0.,
        wspace=0.)

for g in gs:
    ax = plt.subplot(g)
    ax.imshow(_img)
    ax.set_xticks([])
    ax.set_yticks([])
#    ax.set_aspect('auto')

pdf.savefig()
pdf.close()

结果:

如果您希望图像真正覆盖所有可用空间,则可以将宽高比设置为自动:

ax.set_aspect('auto')

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多