cut_image.py 1.16 KB
Newer Older
赵小蒙's avatar
赵小蒙 committed
1
2
from loguru import logger

3
from magic_pdf.config.ocr_content_type import ContentType
赵小蒙's avatar
赵小蒙 committed
4
5
6
7
8
9
10
11
12
13
14
from magic_pdf.libs.commons import join_path
from magic_pdf.libs.pdf_image_tools import cut_image


def ocr_cut_image_and_table(spans, page, page_id, pdf_bytes_md5, imageWriter):
    def return_path(type):
        return join_path(pdf_bytes_md5, type)

    for span in spans:
        span_type = span['type']
        if span_type == ContentType.Image:
赵小蒙's avatar
赵小蒙 committed
15
16
            if not check_img_bbox(span['bbox']):
                continue
赵小蒙's avatar
赵小蒙 committed
17
18
19
            span['image_path'] = cut_image(span['bbox'], page_id, page, return_path=return_path('images'),
                                           imageWriter=imageWriter)
        elif span_type == ContentType.Table:
赵小蒙's avatar
赵小蒙 committed
20
21
            if not check_img_bbox(span['bbox']):
                continue
赵小蒙's avatar
赵小蒙 committed
22
23
24
25
26
27
            span['image_path'] = cut_image(span['bbox'], page_id, page, return_path=return_path('tables'),
                                           imageWriter=imageWriter)

    return spans


赵小蒙's avatar
赵小蒙 committed
28
29
def check_img_bbox(bbox) -> bool:
    if any([bbox[0] >= bbox[2], bbox[1] >= bbox[3]]):
30
        logger.warning(f'image_bboxes: 错误的box, {bbox}')
赵小蒙's avatar
赵小蒙 committed
31
32
        return False
    return True