2

我试图使用 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的示例页面

从 pdf 中截取的快照

4

1 回答 1

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-12-05T13:31:44.620 回答