transforms.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 numpy as np
  16. from PIL import Image
  17. from ....utils import logging
  18. from ...base import BaseTransform
  19. from ...base.predictor.io.writers import ImageWriter
  20. from .keys import SegKeys as K
  21. __all__ = ['GeneratePCMap', 'SaveSegResults']
  22. class GeneratePCMap(BaseTransform):
  23. """ GeneratePCMap """
  24. def __init__(self, color_map=None):
  25. super().__init__()
  26. self.color_map = color_map
  27. def apply(self, data):
  28. """ apply """
  29. pred = data[K.SEG_MAP]
  30. pc_map = self.get_pseudo_color_map(pred)
  31. data[K.PC_MAP] = pc_map
  32. return data
  33. @classmethod
  34. def get_input_keys(cls):
  35. """ get input keys """
  36. return [K.SEG_MAP]
  37. @classmethod
  38. def get_output_keys(cls):
  39. """ get input keys """
  40. return [K.PC_MAP]
  41. def get_pseudo_color_map(self, pred):
  42. """ get_pseudo_color_map """
  43. if pred.min() < 0 or pred.max() > 255:
  44. raise ValueError("`pred` cannot be cast to uint8.")
  45. pred = pred.astype(np.uint8)
  46. pred_mask = Image.fromarray(pred, mode='P')
  47. if self.color_map is None:
  48. color_map = self._get_color_map_list(256)
  49. else:
  50. color_map = self.color_map
  51. pred_mask.putpalette(color_map)
  52. return pred_mask
  53. @staticmethod
  54. def _get_color_map_list(num_classes, custom_color=None):
  55. """ _get_color_map_list """
  56. num_classes += 1
  57. color_map = num_classes * [0, 0, 0]
  58. for i in range(0, num_classes):
  59. j = 0
  60. lab = i
  61. while lab:
  62. color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
  63. color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
  64. color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
  65. j += 1
  66. lab >>= 3
  67. color_map = color_map[3:]
  68. if custom_color:
  69. color_map[:len(custom_color)] = custom_color
  70. return color_map
  71. class SaveSegResults(BaseTransform):
  72. """ SaveSegResults """
  73. _PC_MAP_SUFFIX = '_pc'
  74. _FILE_EXT = '.png'
  75. def __init__(self, save_dir, save_pc_map=True):
  76. super().__init__()
  77. self.save_dir = save_dir
  78. self.save_pc_map = save_pc_map
  79. # We use pillow backend to save both numpy arrays and PIL Image objects
  80. self._writer = ImageWriter(backend='pillow')
  81. def apply(self, data):
  82. """ apply """
  83. seg_map = data[K.SEG_MAP]
  84. ori_path = data[K.IM_PATH]
  85. file_name = os.path.basename(ori_path)
  86. file_name = self._replace_ext(file_name, self._FILE_EXT)
  87. seg_map_save_path = os.path.join(self.save_dir, file_name)
  88. self._write_im(seg_map_save_path, seg_map)
  89. if self.save_pc_map:
  90. if K.PC_MAP in data:
  91. pc_map_save_path = self._add_suffix(seg_map_save_path,
  92. self._PC_MAP_SUFFIX)
  93. pc_map = data[K.PC_MAP]
  94. self._write_im(pc_map_save_path, pc_map)
  95. else:
  96. logging.warning(f"The {K.PC_MAP} result don't exist!")
  97. return data
  98. @classmethod
  99. def get_input_keys(cls):
  100. """ get input keys """
  101. return [K.IM_PATH, K.SEG_MAP]
  102. @classmethod
  103. def get_output_keys(cls):
  104. """ get output keys """
  105. return []
  106. def _write_im(self, path, im):
  107. """ write image """
  108. if os.path.exists(path):
  109. logging.warning(f"{path} already exists. Overwriting it.")
  110. self._writer.write(path, im)
  111. @staticmethod
  112. def _add_suffix(path, suffix):
  113. """ add suffix """
  114. stem, ext = os.path.splitext(path)
  115. return stem + suffix + ext
  116. @staticmethod
  117. def _replace_ext(path, new_ext):
  118. """ replace ext """
  119. stem, _ = os.path.splitext(path)
  120. return stem + new_ext
  121. class PrintResult(BaseTransform):
  122. """ Print Result Transform """
  123. def apply(self, data):
  124. """ apply """
  125. logging.info("The prediction result is:")
  126. logging.info(f"keys: {data.keys()}")
  127. return data
  128. @classmethod
  129. def get_input_keys(cls):
  130. """ get input keys """
  131. return [K.SEG_MAP]
  132. @classmethod
  133. def get_output_keys(cls):
  134. """ get output keys """
  135. return []