topk.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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 pathlib import Path
  15. import json
  16. import PIL
  17. from PIL import ImageDraw, ImageFont
  18. import numpy as np
  19. from ...utils.fonts import PINGFANG_FONT_FILE_PATH
  20. from ...utils import logging
  21. from ..utils.io import JsonWriter, ImageWriter, ImageReader
  22. from ..utils.color_map import get_colormap
  23. class TopkResult(dict):
  24. def __init__(self, data):
  25. super().__init__(data)
  26. self._json_writer = JsonWriter()
  27. self._img_reader = ImageReader(backend="pil")
  28. self._img_writer = ImageWriter(backend="pillow")
  29. def save_json(self, save_path, indent=4, ensure_ascii=False):
  30. if not save_path.endswith(".json"):
  31. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.json"
  32. self._json_writer.write(save_path, self, indent=4, ensure_ascii=False)
  33. def save_img(self, save_path):
  34. if not save_path.lower().endswith((".jpg", ".png")):
  35. save_path = Path(save_path) / f"{Path(self['img_path']).stem}.jpg"
  36. labels = self.get("label_names", self["class_ids"])
  37. res_img = self._draw_label(self["img_path"], self["scores"], labels)
  38. self._img_writer.write(save_path, res_img)
  39. def print(self, json_format=True, indent=4, ensure_ascii=False):
  40. str_ = self
  41. if json_format:
  42. str_ = json.dumps(str_, indent=indent, ensure_ascii=ensure_ascii)
  43. logging.info(str_)
  44. def _draw_label(self, img_path, scores, class_ids):
  45. """Draw label on image"""
  46. label_str = f"{class_ids[0]} {scores[0]:.2f}"
  47. image = self._img_reader.read(img_path)
  48. image = image.convert("RGB")
  49. image_size = image.size
  50. draw = ImageDraw.Draw(image)
  51. min_font_size = int(image_size[0] * 0.02)
  52. max_font_size = int(image_size[0] * 0.05)
  53. for font_size in range(max_font_size, min_font_size - 1, -1):
  54. font = ImageFont.truetype(
  55. PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8"
  56. )
  57. if tuple(map(int, PIL.__version__.split("."))) <= (10, 0, 0):
  58. text_width_tmp, text_height_tmp = draw.textsize(label_str, font)
  59. else:
  60. left, top, right, bottom = draw.textbbox((0, 0), label_str, font)
  61. text_width_tmp, text_height_tmp = right - left, bottom - top
  62. if text_width_tmp <= image_size[0]:
  63. break
  64. else:
  65. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, min_font_size)
  66. color_list = get_colormap(rgb=True)
  67. color = tuple(color_list[0])
  68. font_color = tuple(self._get_font_colormap(3))
  69. if tuple(map(int, PIL.__version__.split("."))) <= (10, 0, 0):
  70. text_width, text_height = draw.textsize(label_str, font)
  71. else:
  72. left, top, right, bottom = draw.textbbox((0, 0), label_str, font)
  73. text_width, text_height = right - left, bottom - top
  74. rect_left = 3
  75. rect_top = 3
  76. rect_right = rect_left + text_width + 3
  77. rect_bottom = rect_top + text_height + 6
  78. draw.rectangle([(rect_left, rect_top), (rect_right, rect_bottom)], fill=color)
  79. text_x = rect_left + 3
  80. text_y = rect_top
  81. draw.text((text_x, text_y), label_str, fill=font_color, font=font)
  82. return image
  83. def _get_font_colormap(self, color_index):
  84. """
  85. Get font colormap
  86. """
  87. dark = np.array([0x14, 0x0E, 0x35])
  88. light = np.array([0xFF, 0xFF, 0xFF])
  89. light_indexs = [0, 3, 4, 8, 9, 13, 14, 18, 19]
  90. if color_index in light_indexs:
  91. return light.astype("int32")
  92. else:
  93. return dark.astype("int32")
  94. # class SaveClsResults(BaseComponent):
  95. # INPUT_KEYS = ["img_path", "cls_pred"]
  96. # OUTPUT_KEYS = None
  97. # DEAULT_INPUTS = {"img_path": "img_path", "cls_pred": "cls_pred"}
  98. # DEAULT_OUTPUTS = {}
  99. # def __init__(self, save_dir, class_ids=None):
  100. # super().__init__()
  101. # self.save_dir = save_dir
  102. # self.class_id_map = _parse_class_id_map(class_ids)
  103. # self._json_writer = ImageWriter(backend="pillow")
  104. # def _write_image(self, path, image):
  105. # """write image"""
  106. # if os.path.exists(path):
  107. # logging.warning(f"{path} already exists. Overwriting it.")
  108. # self._json_writer.write(path, image)