result.py 2.2 KB

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