简体   繁体   English

如何使用python提取图像和图像BBox坐标?

[英]How to extract images and image BBox coordinates using python?

I am trying to extract images in PDF with BBox coordinates of the image.我正在尝试使用图像的 BBox 坐标提取 PDF 中的图像。

I tried using pdfrw library, it is identifying image objects and it have an attribute called media box which have some coordinates, i am not sure if those are correct bbox coordinates since for some pdfs it is showing something like this ['0', '0', '684', '864'] but image doesn't start at the start of the page, so i don't think it is bbox我尝试使用 pdfrw 库,它正在识别图像对象,它有一个名为媒体框的属性,它有一些坐标,我不确定这些是否是正确的 bbox 坐标,因为对于某些 pdf,它显示的内容类似于 ['0', ' 0', '684', '864'] 但图像不是从页面开头开始的,所以我认为它不是 bbox

I tried with following code using pdfrw我尝试使用 pdfrw 使用以下代码

import pdfrw, os
from pdfrw import PdfReader, PdfWriter
from pdfrw.findobjs import page_per_xobj
outfn = 'extract.' + os.path.basename(path)
pages = list(page_per_xobj(PdfReader(path).pages, margin=0.5*72))
writer = PdfWriter(outfn)
writer.addpages(pages)
writer.write()

How do i get image along with it's bbox coordinates?我如何获取图像及其 bbox 坐标?

sample pdf : https://drive.google.com/open?id=1IVbj1b3JfmSv_BJvGUqYvAPVl3FwC2A-示例pdf: https : //drive.google.com/open? id =1IVbj1b3JfmSv_BJvGUqYvAPVl3FwC2A-

I found a way to do it through a library called pdfplumber .我通过一个名为pdfplumber的库找到了一种方法。 It's built on top of pdfminer and is working consistently in my use-case.它建立在 pdfminer 之上,并且在我的用例中始终如一地工作。 And moreover, its MIT licensed so it is helpful for my office work.此外,它的 MIT 许可因此对我的办公室工作很有帮助。

    import pdfplumber

    pdf_obj = pdfplumber.open(doc_path)
    page = pdf_obj.pages[page_no]
    images_in_page = page.images
    page_height = page.height
    image = images_in_page[0] # assuming images_in_page has at least one element, only for understanding purpose. 
    image_bbox = (image['x0'], page_height - image['y1'], image['x1'], page_height - image['y0'])
    cropped_page = page.crop(image_bbox)
    image_obj = cropped_page.to_image(resolution=400)
    image_obj.save(path_to_save_image)

    

Worked well for tables and images in my case.在我的情况下,表格和图像效果很好。

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

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