table_rec.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import cv2
  15. import numpy as np
  16. from pathlib import Path
  17. from .base import BaseResult
  18. from ...utils import logging
  19. from ..utils.io import HtmlWriter, XlsxWriter
  20. class TableRecResult(BaseResult):
  21. """SaveTableResults"""
  22. def __init__(self, data):
  23. super().__init__(data)
  24. self._img_writer.set_backend("pillow")
  25. def _get_res_img(self):
  26. image = self._img_reader.read(self["img_path"])
  27. bbox_res = self["bbox"]
  28. if len(bbox_res) > 0 and len(bbox_res[0]) == 4:
  29. vis_img = self.draw_rectangle(image, bbox_res)
  30. else:
  31. vis_img = self.draw_bbox(image, bbox_res)
  32. return vis_img
  33. def draw_rectangle(self, image, boxes):
  34. """draw_rectangle"""
  35. boxes = np.array(boxes)
  36. img_show = image.copy()
  37. for box in boxes.astype(int):
  38. x1, y1, x2, y2 = box
  39. cv2.rectangle(img_show, (x1, y1), (x2, y2), (255, 0, 0), 2)
  40. return img_show
  41. def draw_bbox(self, image, boxes):
  42. """draw_bbox"""
  43. for box in boxes:
  44. box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
  45. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  46. return image
  47. class StructureTableResult(TableRecResult):
  48. """StructureTableResult"""
  49. def __init__(self, data):
  50. """__init__"""
  51. super().__init__(data)
  52. self._img_writer.set_backend("pillow")
  53. self._html_writer = HtmlWriter()
  54. self._xlsx_writer = XlsxWriter()
  55. def save_to_html(self, save_path):
  56. """save_to_html"""
  57. img_idx = self["img_idx"]
  58. if not save_path.endswith(".html"):
  59. if img_idx > 0:
  60. save_path = (
  61. Path(save_path) / f"{Path(self['img_path']).stem}_{img_idx}.html"
  62. )
  63. else:
  64. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.html"
  65. elif img_idx > 0:
  66. save_path = Path(save_path).stem / f"_{img_idx}.html"
  67. self._html_writer.write(save_path.as_posix(), self["html"])
  68. logging.info(f"The result has been saved in {save_path}.")
  69. def save_to_excel(self, save_path):
  70. """save_to_excel"""
  71. img_idx = self["img_idx"]
  72. if not save_path.endswith(".xlsx"):
  73. if img_idx > 0:
  74. save_path = (
  75. Path(save_path) / f"{Path(self['img_path']).stem}_{img_idx}.xlsx"
  76. )
  77. else:
  78. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.xlsx"
  79. elif img_idx > 0:
  80. save_path = Path(save_path).stem / f"_{img_idx}.xlsx"
  81. self._xlsx_writer.write(save_path.as_posix(), self["html"])
  82. logging.info(f"The result has been saved in {save_path}.")
  83. def save_to_img(self, save_path):
  84. img_idx = self["img_idx"]
  85. if not save_path.endswith((".jpg", ".png")):
  86. if img_idx > 0:
  87. save_path = (
  88. Path(save_path) / f"{Path(self['img_path']).stem}_{img_idx}.jpg"
  89. )
  90. else:
  91. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.jpg"
  92. elif img_idx > 0:
  93. save_path = Path(save_path).stem / f"_{img_idx}.jpg"
  94. else:
  95. save_path = Path(save_path)
  96. res_img = self._get_res_img()
  97. if res_img is not None:
  98. self._img_writer.write(save_path.as_posix(), res_img)
  99. logging.info(f"The result has been saved in {save_path}.")
  100. class TableResult(BaseResult):
  101. """TableResult"""
  102. def __init__(self, data):
  103. """__init__"""
  104. super().__init__(data)
  105. def save_to_img(self, save_path):
  106. if not save_path.lower().endswith((".jpg", ".png")):
  107. img_path = self["img_path"]
  108. save_path = Path(save_path) / f"{Path(img_path).stem}"
  109. else:
  110. save_path = Path(save_path).stem
  111. layout_save_path = f"{save_path}_layout.jpg"
  112. ocr_save_path = f"{save_path}_ocr.jpg"
  113. table_save_path = f"{save_path}_table.jpg"
  114. layout_result = self["layout_result"]
  115. layout_result.save_to_img(layout_save_path)
  116. ocr_result = self["ocr_result"]
  117. ocr_result.save_to_img(ocr_save_path)
  118. for batch_table_result in self["table_result"]:
  119. for table_result in batch_table_result:
  120. table_result.save_to_img(table_save_path)