result.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 copy
  15. import cv2
  16. import numpy as np
  17. from pathlib import Path
  18. import PIL
  19. from PIL import Image, ImageDraw, ImageFont
  20. from ...common.result import BaseCVResult, StrMixin, JsonMixin
  21. class TableRecResult(BaseCVResult):
  22. """SaveTableResults"""
  23. def _get_input_fn(self):
  24. fn = super()._get_input_fn()
  25. if (page_idx := self["page_index"]) is not None:
  26. fp = Path(fn)
  27. stem, suffix = fp.stem, fp.suffix
  28. return f"{stem}_{page_idx}{suffix}"
  29. else:
  30. return fn
  31. def _to_img(self):
  32. image = self["input_img"]
  33. bbox_res = self["bbox"]
  34. if len(bbox_res) > 0 and len(bbox_res[0]) == 4:
  35. vis_img = self.draw_rectangle(image, bbox_res)
  36. else:
  37. vis_img = self.draw_bbox(image, bbox_res)
  38. return {"res": vis_img}
  39. def draw_rectangle(self, image, boxes):
  40. """draw_rectangle"""
  41. boxes = np.array(boxes)
  42. img_show = image.copy()
  43. for box in boxes.astype(int):
  44. x1, y1, x2, y2 = box
  45. cv2.rectangle(img_show, (x1, y1), (x2, y2), (255, 0, 0), 2)
  46. return img_show
  47. def draw_bbox(self, image, boxes):
  48. """draw_bbox"""
  49. for box in boxes:
  50. box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
  51. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  52. return image
  53. def _to_str(self, *args, **kwargs):
  54. data = copy.deepcopy(self)
  55. data.pop("input_img")
  56. return JsonMixin._to_str(data, *args, **kwargs)
  57. def _to_json(self, *args, **kwargs):
  58. data = copy.deepcopy(self)
  59. data.pop("input_img")
  60. return JsonMixin._to_json(data, *args, **kwargs)