transforms.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. "PrintResult",
  27. "SaveClsResults",
  28. "MultiLabelThreshOutput",
  29. ]
  30. def _parse_class_id_map(class_ids):
  31. """parse class id to label map file"""
  32. if class_ids is None:
  33. return None
  34. class_id_map = {id: str(lb) for id, lb in enumerate(class_ids)}
  35. return class_id_map
  36. class PrintResult(BaseTransform):
  37. """Print Result Transform"""
  38. def apply(self, data):
  39. """apply"""
  40. logging.info("The prediction result is:")
  41. logging.info(data[K.CLS_RESULT])
  42. return data
  43. @classmethod
  44. def get_input_keys(cls):
  45. """get input keys"""
  46. return [K.CLS_RESULT]
  47. @classmethod
  48. def get_output_keys(cls):
  49. """get output keys"""
  50. return []
  51. class SaveMLClsResults(BaseTransform):
  52. def __init__(self, save_dir, class_ids=None):
  53. super().__init__()
  54. self.save_dir = save_dir
  55. self.class_id_map = _parse_class_id_map(class_ids)
  56. self._writer = ImageWriter(backend="pillow")
  57. def _get_colormap(self, rgb=False):
  58. """
  59. Get colormap
  60. """
  61. color_list = np.array(
  62. [
  63. 0xFF,
  64. 0x00,
  65. 0x00,
  66. 0xCC,
  67. 0xFF,
  68. 0x00,
  69. 0x00,
  70. 0xFF,
  71. 0x66,
  72. 0x00,
  73. 0x66,
  74. 0xFF,
  75. 0xCC,
  76. 0x00,
  77. 0xFF,
  78. 0xFF,
  79. 0x4D,
  80. 0x00,
  81. 0x80,
  82. 0xFF,
  83. 0x00,
  84. 0x00,
  85. 0xFF,
  86. 0xB2,
  87. 0x00,
  88. 0x1A,
  89. 0xFF,
  90. 0xFF,
  91. 0x00,
  92. 0xE5,
  93. 0xFF,
  94. 0x99,
  95. 0x00,
  96. 0x33,
  97. 0xFF,
  98. 0x00,
  99. 0x00,
  100. 0xFF,
  101. 0xFF,
  102. 0x33,
  103. 0x00,
  104. 0xFF,
  105. 0xFF,
  106. 0x00,
  107. 0x99,
  108. 0xFF,
  109. 0xE5,
  110. 0x00,
  111. 0x00,
  112. 0xFF,
  113. 0x1A,
  114. 0x00,
  115. 0xB2,
  116. 0xFF,
  117. 0x80,
  118. 0x00,
  119. 0xFF,
  120. 0xFF,
  121. 0x00,
  122. 0x4D,
  123. ]
  124. ).astype(np.float32)
  125. color_list = color_list.reshape((-1, 3))
  126. if not rgb:
  127. color_list = color_list[:, ::-1]
  128. return color_list.astype("int32")
  129. def _get_font_colormap(self, color_index):
  130. """
  131. Get font colormap
  132. """
  133. dark = np.array([0x14, 0x0E, 0x35])
  134. light = np.array([0xFF, 0xFF, 0xFF])
  135. light_indexs = [0, 3, 4, 8, 9, 13, 14, 18, 19]
  136. if color_index in light_indexs:
  137. return light.astype("int32")
  138. else:
  139. return dark.astype("int32")
  140. def apply(self, data):
  141. """Draw label on image"""
  142. ori_path = data[K.IM_PATH]
  143. results = data[K.CLS_RESULT]
  144. scores = results[0]["scores"]
  145. label_names = results[0]["label_names"]
  146. file_name = os.path.basename(ori_path)
  147. save_path = os.path.join(self.save_dir, file_name)
  148. image = ImageReader(backend="pil").read(ori_path)
  149. image = image.convert("RGB")
  150. image_width, image_height = image.size
  151. font_size = int(image_width * 0.06)
  152. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, font_size)
  153. text_lines = []
  154. row_width = 0
  155. row_height = 0
  156. row_text = "\t"
  157. for label_name, score in zip(label_names, scores):
  158. text = f"{label_name}({score})\t"
  159. text_width, row_height = font.getsize(text)
  160. if row_width + text_width <= image_width:
  161. row_text += text
  162. row_width += text_width
  163. else:
  164. text_lines.append(row_text)
  165. row_text = "\t" + text
  166. row_width = text_width
  167. text_lines.append(row_text)
  168. color_list = self._get_colormap(rgb=True)
  169. color = tuple(color_list[0])
  170. new_image_height = image_height + len(text_lines) * int(row_height * 1.2)
  171. new_image = Image.new("RGB", (image_width, new_image_height), color)
  172. new_image.paste(image, (0, 0))
  173. draw = ImageDraw.Draw(new_image)
  174. font_color = tuple(self._get_font_colormap(3))
  175. for i, text in enumerate(text_lines):
  176. text_width, _ = font.getsize(text)
  177. draw.text(
  178. (0, image_height + i * int(row_height * 1.2)),
  179. text,
  180. fill=font_color,
  181. font=font,
  182. )
  183. self._write_image(save_path, new_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 []
  198. class MultiLabelThreshOutput(BaseTransform):
  199. def __init__(self, threshold=0.5, class_ids=None, delimiter=None):
  200. super().__init__()
  201. assert isinstance(threshold, (float,))
  202. self.threshold = threshold
  203. self.delimiter = delimiter if delimiter is not None else " "
  204. self.class_id_map = _parse_class_id_map(class_ids)
  205. def apply(self, data):
  206. """apply"""
  207. y = []
  208. x = data[K.CLS_PRED]
  209. pred_index = np.where(x >= self.threshold)[0].astype("int32")
  210. index = pred_index[np.argsort(x[pred_index])][::-1]
  211. clas_id_list = []
  212. score_list = []
  213. label_name_list = []
  214. for i in index:
  215. clas_id_list.append(i.item())
  216. score_list.append(x[i].item())
  217. if self.class_id_map is not None:
  218. label_name_list.append(self.class_id_map[i.item()])
  219. result = {
  220. "class_ids": clas_id_list,
  221. "scores": np.around(score_list, decimals=5).tolist(),
  222. "label_names": label_name_list,
  223. }
  224. y.append(result)
  225. data[K.CLS_RESULT] = y
  226. return data
  227. @classmethod
  228. def get_input_keys(cls):
  229. """get input keys"""
  230. return [K.IM_PATH, K.CLS_PRED]
  231. @classmethod
  232. def get_output_keys(cls):
  233. """get output keys"""
  234. return [K.CLS_RESULT]