cut_image.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from loguru import logger
  2. from magic_pdf.libs.commons import join_path
  3. from magic_pdf.libs.ocr_content_type import ContentType
  4. from magic_pdf.libs.pdf_image_tools import cut_image
  5. def ocr_cut_image_and_table(spans, page, page_id, pdf_bytes_md5, imageWriter):
  6. def return_path(type):
  7. return join_path(pdf_bytes_md5, type)
  8. for span in spans:
  9. span_type = span['type']
  10. if span_type == ContentType.Image:
  11. if not check_img_bbox(span['bbox']):
  12. continue
  13. span['image_path'] = cut_image(span['bbox'], page_id, page, return_path=return_path('images'),
  14. imageWriter=imageWriter)
  15. elif span_type == ContentType.Table:
  16. if not check_img_bbox(span['bbox']):
  17. continue
  18. span['image_path'] = cut_image(span['bbox'], page_id, page, return_path=return_path('tables'),
  19. imageWriter=imageWriter)
  20. return spans
  21. def txt_save_images_by_bboxes(page_num: int, page, pdf_bytes_md5: str,
  22. image_bboxes: list, images_overlap_backup: list, table_bboxes: list,
  23. equation_inline_bboxes: list,
  24. equation_interline_bboxes: list, imageWriter) -> dict:
  25. """
  26. 返回一个dict, key为bbox, 值是图片地址
  27. """
  28. image_info = []
  29. image_backup_info = []
  30. table_info = []
  31. inline_eq_info = []
  32. interline_eq_info = []
  33. # 图片的保存路径组成是这样的: {s3_or_local_path}/{book_name}/{images|tables|equations}/{page_num}_{bbox[0]}_{bbox[1]}_{bbox[2]}_{bbox[3]}.jpg
  34. def return_path(type):
  35. return join_path(pdf_bytes_md5, type)
  36. for bbox in image_bboxes:
  37. if not check_img_bbox(bbox):
  38. continue
  39. image_path = cut_image(bbox, page_num, page, return_path("images"), imageWriter)
  40. image_info.append({"bbox": bbox, "image_path": image_path})
  41. for bbox in images_overlap_backup:
  42. if not check_img_bbox(bbox):
  43. continue
  44. image_path = cut_image(bbox, page_num, page, return_path("images"), imageWriter)
  45. image_backup_info.append({"bbox": bbox, "image_path": image_path})
  46. for bbox in table_bboxes:
  47. if not check_img_bbox(bbox):
  48. continue
  49. image_path = cut_image(bbox, page_num, page, return_path("tables"), imageWriter)
  50. table_info.append({"bbox": bbox, "image_path": image_path})
  51. return image_info, image_backup_info, table_info, inline_eq_info, interline_eq_info
  52. def check_img_bbox(bbox) -> bool:
  53. if any([bbox[0] >= bbox[2], bbox[1] >= bbox[3]]):
  54. logger.warning(f"image_bboxes: 错误的box, {bbox}")
  55. return False
  56. return True