seg.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 numpy as np
  15. import PIL
  16. from PIL import Image
  17. import copy
  18. import json
  19. from ...utils import logging
  20. from .utils.mixin import ImgMixin
  21. from .base import CVResult
  22. class SegResult(CVResult):
  23. """Save Result Transform"""
  24. def __init__(self, data):
  25. super().__init__(data)
  26. self._img_writer.set_backend("pillow", format_="PNG")
  27. def _to_img(self):
  28. """apply"""
  29. seg_map = self["pred"]
  30. pc_map = self.get_pseudo_color_map(seg_map[0])
  31. return pc_map
  32. def get_pseudo_color_map(self, pred):
  33. """get_pseudo_color_map"""
  34. if pred.min() < 0 or pred.max() > 255:
  35. raise ValueError("`pred` cannot be cast to uint8.")
  36. pred = pred.astype(np.uint8)
  37. pred_mask = Image.fromarray(pred, mode="P")
  38. color_map = self._get_color_map_list(256)
  39. pred_mask.putpalette(color_map)
  40. return pred_mask
  41. @staticmethod
  42. def _get_color_map_list(num_classes, custom_color=None):
  43. """_get_color_map_list"""
  44. num_classes += 1
  45. color_map = num_classes * [0, 0, 0]
  46. for i in range(0, num_classes):
  47. j = 0
  48. lab = i
  49. while lab:
  50. color_map[i * 3] |= ((lab >> 0) & 1) << (7 - j)
  51. color_map[i * 3 + 1] |= ((lab >> 1) & 1) << (7 - j)
  52. color_map[i * 3 + 2] |= ((lab >> 2) & 1) << (7 - j)
  53. j += 1
  54. lab >>= 3
  55. color_map = color_map[3:]
  56. if custom_color:
  57. color_map[: len(custom_color)] = custom_color
  58. return color_map
  59. def _to_str(self, _, *args, **kwargs):
  60. data = copy.deepcopy(self)
  61. data["pred"] = "..."
  62. return super()._to_str(data, *args, **kwargs)