base.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. from abc import abstractmethod
  15. from pathlib import Path
  16. import json
  17. from ...utils import logging
  18. from ..utils.io import JsonWriter, ImageReader, ImageWriter
  19. class BaseResult(dict):
  20. def __init__(self, data):
  21. super().__init__(data)
  22. self._json_writer = JsonWriter()
  23. self._img_reader = ImageReader(backend="opencv")
  24. self._img_writer = ImageWriter(backend="opencv")
  25. def save_to_json(self, save_path, indent=4, ensure_ascii=False):
  26. if not save_path.endswith(".json"):
  27. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.json"
  28. self._json_writer.write(save_path, self, indent=4, ensure_ascii=False)
  29. def save_to_img(self, save_path):
  30. if not save_path.lower().endswith((".jpg", ".png")):
  31. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.jpg"
  32. res_img = self._get_res_img()
  33. if res_img is not None:
  34. self._img_writer.write(save_path.as_posix(), res_img)
  35. logging.info(f"The result has been saved in {save_path}.")
  36. def print(self, json_format=True, indent=4, ensure_ascii=False):
  37. str_ = self
  38. if json_format:
  39. str_ = json.dumps(str_, indent=indent, ensure_ascii=ensure_ascii)
  40. logging.info(str_)
  41. @abstractmethod
  42. def _get_res_img(self):
  43. raise NotImplementedError