transforms.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 os
  15. import json
  16. from PIL import Image, ImageDraw, ImageFont
  17. from pathlib import Path
  18. import numpy as np
  19. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  20. from ...base import BaseTransform
  21. from ...base.predictor.io.writers import ImageWriter
  22. from .keys import ClsKeys as K
  23. from ....utils import logging
  24. __all__ = ["Topk", "NormalizeFeatures", "PrintResult", "SaveClsResults"]
  25. def _parse_class_id_map(class_ids):
  26. """ parse class id to label map file """
  27. if class_ids is None:
  28. return None
  29. class_id_map = {id: str(lb) for id, lb in enumerate(class_ids)}
  30. return class_id_map
  31. class Topk(BaseTransform):
  32. """ Topk Transform """
  33. def __init__(self, topk, class_ids=None):
  34. super().__init__()
  35. assert isinstance(topk, (int, ))
  36. self.topk = topk
  37. self.class_id_map = _parse_class_id_map(class_ids)
  38. def apply(self, data):
  39. """ apply """
  40. x = data[K.CLS_PRED]
  41. class_id_map = self.class_id_map
  42. y = []
  43. index = x.argsort(axis=0)[-self.topk:][::-1].astype("int32")
  44. clas_id_list = []
  45. score_list = []
  46. label_name_list = []
  47. for i in index:
  48. clas_id_list.append(i.item())
  49. score_list.append(x[i].item())
  50. if class_id_map is not None:
  51. label_name_list.append(class_id_map[i.item()])
  52. result = {
  53. "class_ids": clas_id_list,
  54. "scores": np.around(
  55. score_list, decimals=5).tolist()
  56. }
  57. if label_name_list is not None:
  58. result["label_names"] = label_name_list
  59. y.append(result)
  60. data[K.CLS_RESULT] = y
  61. return data
  62. @classmethod
  63. def get_input_keys(cls):
  64. """ get input keys """
  65. return [K.IM_PATH, K.CLS_PRED]
  66. @classmethod
  67. def get_output_keys(cls):
  68. """ get output keys """
  69. return [K.CLS_RESULT]
  70. class NormalizeFeatures(BaseTransform):
  71. """ Normalize Features Transform """
  72. def apply(self, data):
  73. """ apply """
  74. x = data[K.CLS_PRED]
  75. feas_norm = np.sqrt(np.sum(np.square(x), axis=0, keepdims=True))
  76. x = np.divide(x, feas_norm)
  77. data[K.CLS_RESULT] = x
  78. return data
  79. @classmethod
  80. def get_input_keys(cls):
  81. """ get input keys """
  82. return [K.IM_PATH, K.CLS_PRED]
  83. @classmethod
  84. def get_output_keys(cls):
  85. """ get output keys """
  86. return [K.CLS_RESULT]
  87. class PrintResult(BaseTransform):
  88. """ Print Result Transform """
  89. def apply(self, data):
  90. """ apply """
  91. logging.info("The prediction result is:")
  92. logging.info(data[K.CLS_RESULT])
  93. return data
  94. @classmethod
  95. def get_input_keys(cls):
  96. """ get input keys """
  97. return [K.CLS_RESULT]
  98. @classmethod
  99. def get_output_keys(cls):
  100. """ get output keys """
  101. return []
  102. class SaveClsResults(BaseTransform):
  103. def __init__(self, save_dir, class_ids=None):
  104. super().__init__()
  105. self.save_dir = save_dir
  106. self.class_id_map = _parse_class_id_map(class_ids)
  107. self._writer = ImageWriter(backend='pillow')
  108. def _get_colormap(self, rgb=False):
  109. """
  110. Get colormap
  111. """
  112. color_list = np.array([
  113. 0xFF, 0x00, 0x00, 0xCC, 0xFF, 0x00, 0x00, 0xFF, 0x66, 0x00, 0x66,
  114. 0xFF, 0xCC, 0x00, 0xFF, 0xFF, 0x4D, 0x00, 0x80, 0xff, 0x00, 0x00,
  115. 0xFF, 0xB2, 0x00, 0x1A, 0xFF, 0xFF, 0x00, 0xE5, 0xFF, 0x99, 0x00,
  116. 0x33, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0x33, 0x00, 0xFF, 0xff, 0x00,
  117. 0x99, 0xFF, 0xE5, 0x00, 0x00, 0xFF, 0x1A, 0x00, 0xB2, 0xFF, 0x80,
  118. 0x00, 0xFF, 0xFF, 0x00, 0x4D
  119. ]).astype(np.float32)
  120. color_list = (color_list.reshape((-1, 3)))
  121. if not rgb:
  122. color_list = color_list[:, ::-1]
  123. return color_list.astype('int32')
  124. def _get_font_colormap(self, color_index):
  125. """
  126. Get font colormap
  127. """
  128. dark = np.array([0x14, 0x0E, 0x35])
  129. light = np.array([0xFF, 0xFF, 0xFF])
  130. light_indexs = [0, 3, 4, 8, 9, 13, 14, 18, 19]
  131. if color_index in light_indexs:
  132. return light.astype('int32')
  133. else:
  134. return dark.astype('int32')
  135. def apply(self, data):
  136. """ Draw label on image """
  137. ori_path = data[K.IM_PATH]
  138. pred = data[K.CLS_PRED]
  139. index = pred.argsort(axis=0)[-1].astype("int32")
  140. score = pred[index].item()
  141. label = self.class_id_map[int(index)] if self.class_id_map else ""
  142. label_str = f"{label} {score:.2f}"
  143. file_name = os.path.basename(ori_path)
  144. save_path = os.path.join(self.save_dir, file_name)
  145. image = Image.open(ori_path)
  146. image = image.convert('RGB')
  147. image_size = image.size
  148. draw = ImageDraw.Draw(image)
  149. min_font_size = int(image_size[0] * 0.02)
  150. max_font_size = int(image_size[0] * 0.05)
  151. for font_size in range(max_font_size, min_font_size - 1, -1):
  152. font = ImageFont.truetype(
  153. PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8")
  154. text_width_tmp, text_height_tmp = draw.textsize(label_str, font)
  155. if text_width_tmp <= image_size[0]:
  156. break
  157. else:
  158. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH,
  159. min_font_size)
  160. color_list = self._get_colormap(rgb=True)
  161. color = tuple(color_list[0])
  162. font_color = tuple(self._get_font_colormap(3))
  163. text_width, text_height = draw.textsize(label_str, font)
  164. rect_left = 3
  165. rect_top = 3
  166. rect_right = rect_left + text_width + 3
  167. rect_bottom = rect_top + text_height + 6
  168. draw.rectangle(
  169. [(rect_left, rect_top), (rect_right, rect_bottom)], fill=color)
  170. text_x = rect_left + 3
  171. text_y = rect_top
  172. draw.text((text_x, text_y), label_str, fill=font_color, font=font)
  173. self._write_image(save_path, image)
  174. return data
  175. def _write_image(self, path, image):
  176. """ write image """
  177. if os.path.exists(path):
  178. logging.warning(f"{path} already exists. Overwriting it.")
  179. self._writer.write(path, image)
  180. @classmethod
  181. def get_input_keys(cls):
  182. """ get input keys """
  183. return [K.IM_PATH, K.CLS_PRED]
  184. @classmethod
  185. def get_output_keys(cls):
  186. """ get output keys """
  187. return []