transforms.py 7.5 KB

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