transforms.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. "MultiLabelThreshOutput",
  31. ]
  32. def _parse_class_id_map(class_ids):
  33. """parse class id to label map file"""
  34. if class_ids is None:
  35. return None
  36. class_id_map = {id: str(lb) for id, lb in enumerate(class_ids)}
  37. return class_id_map
  38. class Topk(BaseTransform):
  39. """Topk Transform"""
  40. def __init__(self, topk, class_ids=None):
  41. super().__init__()
  42. assert isinstance(topk, (int,))
  43. self.topk = topk
  44. self.class_id_map = _parse_class_id_map(class_ids)
  45. def apply(self, data):
  46. """apply"""
  47. x = data[K.CLS_PRED]
  48. class_id_map = self.class_id_map
  49. y = []
  50. index = x.argsort(axis=0)[-self.topk :][::-1].astype("int32")
  51. clas_id_list = []
  52. score_list = []
  53. label_name_list = []
  54. for i in index:
  55. clas_id_list.append(i.item())
  56. score_list.append(x[i].item())
  57. if class_id_map is not None:
  58. label_name_list.append(class_id_map[i.item()])
  59. result = {
  60. "class_ids": clas_id_list,
  61. "scores": np.around(score_list, decimals=5).tolist(),
  62. }
  63. if label_name_list is not None:
  64. result["label_names"] = label_name_list
  65. y.append(result)
  66. data[K.CLS_RESULT] = y
  67. return data
  68. @classmethod
  69. def get_input_keys(cls):
  70. """get input keys"""
  71. return [K.IM_PATH, K.CLS_PRED]
  72. @classmethod
  73. def get_output_keys(cls):
  74. """get output keys"""
  75. return [K.CLS_RESULT]
  76. class NormalizeFeatures(BaseTransform):
  77. """Normalize Features Transform"""
  78. def apply(self, data):
  79. """apply"""
  80. x = data[K.CLS_PRED]
  81. feas_norm = np.sqrt(np.sum(np.square(x), axis=0, keepdims=True))
  82. x = np.divide(x, feas_norm)
  83. data[K.CLS_RESULT] = x
  84. return data
  85. @classmethod
  86. def get_input_keys(cls):
  87. """get input keys"""
  88. return [K.IM_PATH, K.CLS_PRED]
  89. @classmethod
  90. def get_output_keys(cls):
  91. """get output keys"""
  92. return [K.CLS_RESULT]
  93. class PrintResult(BaseTransform):
  94. """Print Result Transform"""
  95. def apply(self, data):
  96. """apply"""
  97. logging.info("The prediction result is:")
  98. logging.info(data[K.CLS_RESULT])
  99. return data
  100. @classmethod
  101. def get_input_keys(cls):
  102. """get input keys"""
  103. return [K.CLS_RESULT]
  104. @classmethod
  105. def get_output_keys(cls):
  106. """get output keys"""
  107. return []
  108. class SaveClsResults(BaseTransform):
  109. def __init__(self, save_dir, class_ids=None):
  110. super().__init__()
  111. self.save_dir = save_dir
  112. self.class_id_map = _parse_class_id_map(class_ids)
  113. self._writer = ImageWriter(backend="pillow")
  114. def _get_colormap(self, rgb=False):
  115. """
  116. Get colormap
  117. """
  118. color_list = np.array(
  119. [
  120. 0xFF,
  121. 0x00,
  122. 0x00,
  123. 0xCC,
  124. 0xFF,
  125. 0x00,
  126. 0x00,
  127. 0xFF,
  128. 0x66,
  129. 0x00,
  130. 0x66,
  131. 0xFF,
  132. 0xCC,
  133. 0x00,
  134. 0xFF,
  135. 0xFF,
  136. 0x4D,
  137. 0x00,
  138. 0x80,
  139. 0xFF,
  140. 0x00,
  141. 0x00,
  142. 0xFF,
  143. 0xB2,
  144. 0x00,
  145. 0x1A,
  146. 0xFF,
  147. 0xFF,
  148. 0x00,
  149. 0xE5,
  150. 0xFF,
  151. 0x99,
  152. 0x00,
  153. 0x33,
  154. 0xFF,
  155. 0x00,
  156. 0x00,
  157. 0xFF,
  158. 0xFF,
  159. 0x33,
  160. 0x00,
  161. 0xFF,
  162. 0xFF,
  163. 0x00,
  164. 0x99,
  165. 0xFF,
  166. 0xE5,
  167. 0x00,
  168. 0x00,
  169. 0xFF,
  170. 0x1A,
  171. 0x00,
  172. 0xB2,
  173. 0xFF,
  174. 0x80,
  175. 0x00,
  176. 0xFF,
  177. 0xFF,
  178. 0x00,
  179. 0x4D,
  180. ]
  181. ).astype(np.float32)
  182. color_list = color_list.reshape((-1, 3))
  183. if not rgb:
  184. color_list = color_list[:, ::-1]
  185. return color_list.astype("int32")
  186. def _get_font_colormap(self, color_index):
  187. """
  188. Get font colormap
  189. """
  190. dark = np.array([0x14, 0x0E, 0x35])
  191. light = np.array([0xFF, 0xFF, 0xFF])
  192. light_indexs = [0, 3, 4, 8, 9, 13, 14, 18, 19]
  193. if color_index in light_indexs:
  194. return light.astype("int32")
  195. else:
  196. return dark.astype("int32")
  197. def apply(self, data):
  198. """Draw label on image"""
  199. ori_path = data[K.IM_PATH]
  200. pred = data[K.CLS_PRED]
  201. index = pred.argsort(axis=0)[-1].astype("int32")
  202. score = pred[index].item()
  203. label = self.class_id_map[int(index)] if self.class_id_map else ""
  204. label_str = f"{label} {score:.2f}"
  205. file_name = os.path.basename(ori_path)
  206. save_path = os.path.join(self.save_dir, file_name)
  207. image = ImageReader(backend="pil").read(ori_path)
  208. image = image.convert("RGB")
  209. image_size = image.size
  210. draw = ImageDraw.Draw(image)
  211. min_font_size = int(image_size[0] * 0.02)
  212. max_font_size = int(image_size[0] * 0.05)
  213. for font_size in range(max_font_size, min_font_size - 1, -1):
  214. font = ImageFont.truetype(
  215. PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8"
  216. )
  217. if tuple(map(int, PIL.__version__.split("."))) <= (10, 0, 0):
  218. text_width_tmp, text_height_tmp = draw.textsize(label_str, font)
  219. else:
  220. left, top, right, bottom = draw.textbbox((0, 0), label_str, font)
  221. text_width_tmp, text_height_tmp = right - left, bottom - top
  222. if text_width_tmp <= image_size[0]:
  223. break
  224. else:
  225. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, min_font_size)
  226. color_list = self._get_colormap(rgb=True)
  227. color = tuple(color_list[0])
  228. font_color = tuple(self._get_font_colormap(3))
  229. if tuple(map(int, PIL.__version__.split("."))) <= (10, 0, 0):
  230. text_width, text_height = draw.textsize(label_str, font)
  231. else:
  232. left, top, right, bottom = draw.textbbox((0, 0), label_str, font)
  233. text_width, text_height = right - left, bottom - top
  234. rect_left = 3
  235. rect_top = 3
  236. rect_right = rect_left + text_width + 3
  237. rect_bottom = rect_top + text_height + 6
  238. draw.rectangle([(rect_left, rect_top), (rect_right, rect_bottom)], fill=color)
  239. text_x = rect_left + 3
  240. text_y = rect_top
  241. draw.text((text_x, text_y), label_str, fill=font_color, font=font)
  242. self._write_image(save_path, image)
  243. return data
  244. def _write_image(self, path, image):
  245. """write image"""
  246. if os.path.exists(path):
  247. logging.warning(f"{path} already exists. Overwriting it.")
  248. self._writer.write(path, image)
  249. @classmethod
  250. def get_input_keys(cls):
  251. """get input keys"""
  252. return [K.IM_PATH, K.CLS_PRED]
  253. @classmethod
  254. def get_output_keys(cls):
  255. """get output keys"""
  256. return []
  257. class MultiLabelThreshOutput(BaseTransform):
  258. def __init__(self, threshold=0.5, class_ids=None, delimiter=None):
  259. super().__init__()
  260. assert isinstance(threshold, (float,))
  261. self.threshold = threshold
  262. self.delimiter = delimiter if delimiter is not None else " "
  263. self.class_id_map = _parse_class_id_map(class_ids)
  264. def apply(self, data):
  265. """apply"""
  266. y = []
  267. x = data[K.CLS_PRED]
  268. pred_index = np.where(x >= self.threshold)[0].astype("int32")
  269. index = pred_index[np.argsort(x[pred_index])][::-1]
  270. clas_id_list = []
  271. score_list = []
  272. label_name_list = []
  273. for i in index:
  274. clas_id_list.append(i.item())
  275. score_list.append(x[i].item())
  276. if self.class_id_map is not None:
  277. label_name_list.append(self.class_id_map[i.item()])
  278. result = {
  279. "class_ids": clas_id_list,
  280. "scores": np.around(score_list, decimals=5).tolist(),
  281. "label_names": label_name_list,
  282. }
  283. y.append(result)
  284. data[K.CLS_RESULT] = y
  285. return data
  286. @classmethod
  287. def get_input_keys(cls):
  288. """get input keys"""
  289. return [K.IM_PATH, K.CLS_PRED]
  290. @classmethod
  291. def get_output_keys(cls):
  292. """get output keys"""
  293. return [K.CLS_RESULT]
  294. class SaveMLClsResults(SaveClsResults, BaseTransform):
  295. def __init__(self, save_dir, class_ids=None):
  296. super().__init__(save_dir=save_dir)
  297. self.save_dir = save_dir
  298. self.class_id_map = _parse_class_id_map(class_ids)
  299. self._writer = ImageWriter(backend="pillow")
  300. def apply(self, data):
  301. """Draw label on image"""
  302. ori_path = data[K.IM_PATH]
  303. results = data[K.CLS_RESULT]
  304. scores = results[0]["scores"]
  305. label_names = results[0]["label_names"]
  306. file_name = os.path.basename(ori_path)
  307. save_path = os.path.join(self.save_dir, file_name)
  308. image = ImageReader(backend="pil").read(ori_path)
  309. image = image.convert("RGB")
  310. image_width, image_height = image.size
  311. font_size = int(image_width * 0.06)
  312. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, font_size)
  313. text_lines = []
  314. row_width = 0
  315. row_height = 0
  316. row_text = "\t"
  317. for label_name, score in zip(label_names, scores):
  318. text = f"{label_name}({score})\t"
  319. text_width, row_height = font.getsize(text)
  320. if row_width + text_width <= image_width:
  321. row_text += text
  322. row_width += text_width
  323. else:
  324. text_lines.append(row_text)
  325. row_text = "\t" + text
  326. row_width = text_width
  327. text_lines.append(row_text)
  328. color_list = self._get_colormap(rgb=True)
  329. color = tuple(color_list[0])
  330. new_image_height = image_height + len(text_lines) * int(row_height * 1.2)
  331. new_image = Image.new("RGB", (image_width, new_image_height), color)
  332. new_image.paste(image, (0, 0))
  333. draw = ImageDraw.Draw(new_image)
  334. font_color = tuple(self._get_font_colormap(3))
  335. for i, text in enumerate(text_lines):
  336. text_width, _ = font.getsize(text)
  337. draw.text(
  338. (0, image_height + i * int(row_height * 1.2)),
  339. text,
  340. fill=font_color,
  341. font=font,
  342. )
  343. self._write_image(save_path, new_image)
  344. return data