result.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. import numpy as np
  16. from ....utils.deps import class_requires_deps, is_dep_available
  17. from ...common.result import BaseCVResult, JsonMixin
  18. if is_dep_available("opencv-contrib-python"):
  19. import cv2
  20. @class_requires_deps("opencv-contrib-python")
  21. class TableRecResult(BaseCVResult):
  22. """SaveTableResults"""
  23. def _to_img(self):
  24. image = self["input_img"]
  25. bbox_res = self["bbox"]
  26. if len(bbox_res) > 0 and len(bbox_res[0]) == 4:
  27. vis_img = self.draw_rectangle(image, bbox_res)
  28. else:
  29. vis_img = self.draw_bbox(image, bbox_res)
  30. return {"res": vis_img}
  31. def draw_rectangle(self, image, boxes):
  32. """draw_rectangle"""
  33. boxes = np.array(boxes)
  34. img_show = image.copy()
  35. for box in boxes.astype(int):
  36. x1, y1, x2, y2 = box
  37. cv2.rectangle(img_show, (x1, y1), (x2, y2), (255, 0, 0), 2)
  38. return img_show
  39. def draw_bbox(self, image, boxes):
  40. """draw_bbox"""
  41. for box in boxes:
  42. box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
  43. image = cv2.polylines(np.array(image), [box], True, (255, 0, 0), 2)
  44. return image
  45. def _to_str(self, *args, **kwargs):
  46. data = copy.deepcopy(self)
  47. data.pop("input_img")
  48. return JsonMixin._to_str(data, *args, **kwargs)
  49. def _to_json(self, *args, **kwargs):
  50. data = copy.deepcopy(self)
  51. data.pop("input_img")
  52. return JsonMixin._to_json(data, *args, **kwargs)