【问题标题】:Paste PDF image into Pyplot figure将 PDF 图像粘贴到 Pyplot 图中
【发布时间】:2019-02-21 13:07:33
【问题描述】:

如何将 PDF 文件中的图像绘制到 Pyplot 图形中(例如使用plt.imshow,或者在我可以使用ax.add_artist 添加的某个容器中)?


无效的方法:

import matplotlib.pyplot as plt
im = plt.imread('file.pdf')

(来源:this question,它适用于 PNG 文件。)

from PIL import Image
im = Image.open('file.pdf')

(来源:this doc,但同样是doesn't work for PDF files;该问题链接了一个库以阅读 PDF,但该文档没有显示将它们添加到 Pyplot 图中的明显方法。)

另外,this question 存在,但答案无需实际加载 PDF 文件即可解决问题。

【问题讨论】:

  • 据我所知,matplotlib 和枕头(matplotlib 将在后台用于此类任务)都无法阅读 pdf。通常的策略是将您的 pdf 转换为 png 等可读格式并读入,例如通过imread。有许多转换工具。我个人会使用inkscape。但也有可用的 python 工具,参见例如herehere.
  • 为什么不将您的文件转换为可读格式?

标签: python pdf matplotlib


【解决方案1】:

有一个名为 PyMuPDF 的模块可以让这项工作变得更容易。

将 PDF 图像抓取到 PIL 图像中

  1. 要从每个页面中抓取单独的图像,可以找到 herehere 关于如何将它们转换为 PIL 格式的教程。

  2. 如果打算抓取整个 PDF 页面或页面,page.get_pixmap() 记录的here 可以做到这一点。

下面的 sn-p 显示了如何遍历并抓取 PDF 的每一页作为PIL.Image

import io
import fitz
from PIL import Image

file = 'myfile.pdf'
pdf_file = fitz.open(file)

# in case there is a need to loop through multiple PDF pages
for page_number in range(len(pdf_file)):
    page = pdf_file[page_number]
    rgb = page.get_pixmap()
    pil_image = Image.open(io.BytesIO(rgb.tobytes()))

    # display code or image manipulation here for each page #

显示抓取的 PDF 图像

在任何一种情况下,一旦存在PIL.Image 对象,例如上面的pil_image 变量,show() 函数就可以显示它(并且根据操作系统的不同会有所不同)。但是,如果偏好使用matplotlib.pyplot.imshow,则必须先将PIL.Image 转换为RGB。

显示PIL.Imagepyplot.imshow 的片段

import matplotlib.pyplot as plt

plt.imshow(pil_image.convert('RGB'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多