【问题标题】:Python Image extraction sequence from pdfPython从pdf中提取图像序列
【发布时间】:2021-03-14 19:29:03
【问题描述】:

我试图使用 PyMuPDF (fitz) 从 pdf 中提取图像。我的 pdf 在一个页面中有多个图像。我在保存图像时保持正确的序列号。我看到被提取的图像没有遵循正确的顺序。有时它从底部开始提取,有时从顶部开始等等。有没有办法修改我的代码,以便提取遵循正确的顺序? 下面给出的是我正在使用的代码:

import fitz
from PIL import Image
filename = "document.pdf"
doc = fitz.open(filename)

for i in range(len(doc)):
    img_num = 0
    p_no = 1
    for img in doc.getPageImageList(i):
        xref = img[0]
        pix = fitz.Pixmap(doc, xref)
        if pix.n - pix.alpha < 4:
            img_num += 1       
            pix.writeImage("%s-%s.jpg" % (str(p_no),str(img_num)))
        else:
            img_num += 1              
            pix1 = fitz.Pixmap(fitz.csRGB, pix)
            pix1.writeImage("%s-%s.jpg" % (str(p_no),str(img_num)))
            pix1 = None
        pix = None
        p_no += 1

下面是pdf的示例页面

【问题讨论】:

  • for img in doc.getPageImageList(i).sort() 也许?
  • 不。不工作。我收到以下错误:TypeError: 'NoneType' object is not iterable

标签: python pymupdf image-extraction


【解决方案1】:

我有同样的问题,我使用了以下代码:

import fitz 
import io
from PIL import Image


file = "file_path"
pdf_file = fitz.open(file)


for page_index in range(len(pdf_file)):
    # get the page itself
    page = pdf_file[page_index]
    image_list = page.getImageList()
    # printing number of images found in this page
    if image_list:
        print(f"[+] Found  {len(image_list)} images in page {page_index}")
    else:
        print("[!] No images found on the given pdf page", page_index)
    for image_index, img in enumerate(page.getImageList(), start=1):
        print(img)
        print(image_index)
        # get the XREF of the image
        xref = img[0]
        # extract the image bytes
        base_image = pdf_file.extractImage(xref)
        image_bytes = base_image["image"]
        # get the image extension
        image_ext = base_image["ext"]
        # load it to PIL
        image = Image.open(io.BytesIO(image_bytes))
        # save it to local disk
        image.save(open(f"image{page_index+1}_{image_index}.{image_ext}", "wb")) 

最可能的方法是找到“img”变量并对其进行排序。 我很想听听任何进一步的建议,或者如果您找到更好的想法/解决方案。

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2019-10-15
    • 2013-12-18
    • 2011-01-29
    • 2015-01-27
    • 1970-01-01
    • 2021-10-19
    • 2019-11-14
    相关资源
    最近更新 更多