result.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 copy
  15. import numpy as np
  16. from PIL import Image
  17. from ...common.result import BaseCVResult, JsonMixin
  18. class SegResult(BaseCVResult):
  19. """Save Result Transform"""
  20. def _to_img(self):
  21. """apply"""
  22. seg_map = self["pred"]
  23. pc_map = self.get_pseudo_color_map(seg_map[0])
  24. if pc_map.mode == "P":
  25. pc_map = pc_map.convert("RGB")
  26. return {"res": pc_map}
  27. def get_pseudo_color_map(self, pred):
  28. """get_pseudo_color_map"""
  29. if pred.min() < 0 or pred.max() > 255:
  30. raise ValueError("`pred` cannot be cast to uint8.")
  31. pred = pred.astype(np.uint8)
  32. pred_mask = Image.fromarray(pred, mode="P")
  33. color_map = self._get_color_map_list(256)
  34. pred_mask.putpalette(color_map)
  35. return pred_mask
  36. @staticmethod
  37. def _get_color_map_list(num_classes, custom_color=None):
  38. """_get_color_map_list"""
  39. num_classes += 1
  40. color_map = num_classes * [0, 0, 0]
  41. for i in range(0, num_classes):
  42. j = 0
  43. lab = i
  44. while lab:
  45. color_map[i * 3] |= ((lab >> 0) & 1) << (7 - j)
  46. color_map[i * 3 + 1] |= ((lab >> 1) & 1) << (7 - j)
  47. color_map[i * 3 + 2] |= ((lab >> 2) & 1) << (7 - j)
  48. j += 1
  49. lab >>= 3
  50. color_map = color_map[3:]
  51. if custom_color:
  52. color_map[: len(custom_color)] = custom_color
  53. return color_map
  54. def _to_str(self, *args, **kwargs):
  55. data = copy.deepcopy(self)
  56. data.pop("input_img")
  57. data["pred"] = "..."
  58. return JsonMixin._to_str(data, *args, **kwargs)
  59. def _to_json(self, *args, **kwargs):
  60. data = copy.deepcopy(self)
  61. data.pop("input_img")
  62. return JsonMixin._to_json(data, *args, **kwargs)