繁体   English   中英

将 PDF 图像粘贴到 Pyplot 图中

[英]Paste PDF image into Pyplot figure

如何将 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 ,但同样,它不适用于 PDF 文件;问题将库链接到阅读 PDF,但 doc 没有显示将它们添加到 Pyplot 图中的明显方法。)

此外, 这个问题存在,但答案在没有实际加载 PDF 文件的情况下解决了问题。

有一个名为 PyMuPDF 的模块使这项工作变得容易得多。

将 PDF 图像刮成 PIL 图像

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

  2. 如果打算获取整个 PDF 页面或页面, 此处记录的page.get_pixmap()可以执行此操作。

下面的代码片段展示了如何遍历并抓取 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。

pyplot.imshow显示PIL.Image的片段

import matplotlib.pyplot as plt

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM