transforms.py 8.3 KB

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