result.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 UadResult(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. return {"res": pc_map}
  25. def get_pseudo_color_map(self, pred):
  26. """get_pseudo_color_map"""
  27. if pred.min() < 0 or pred.max() > 255:
  28. raise ValueError("`pred` cannot be cast to uint8.")
  29. pred = pred.astype(np.uint8)
  30. pred_mask = Image.fromarray(pred, mode="P")
  31. color_map = self._get_color_map_list(256)
  32. pred_mask.putpalette(color_map)
  33. return pred_mask
  34. @staticmethod
  35. def _get_color_map_list(num_classes, custom_color=None):
  36. """_get_color_map_list"""
  37. num_classes += 1
  38. color_map = num_classes * [0, 0, 0]
  39. for i in range(0, num_classes):
  40. j = 0
  41. lab = i
  42. while lab:
  43. color_map[i * 3] |= ((lab >> 0) & 1) << (7 - j)
  44. color_map[i * 3 + 1] |= ((lab >> 1) & 1) << (7 - j)
  45. color_map[i * 3 + 2] |= ((lab >> 2) & 1) << (7 - j)
  46. j += 1
  47. lab >>= 3
  48. color_map = color_map[3:]
  49. if custom_color:
  50. color_map[: len(custom_color)] = custom_color
  51. return color_map
  52. def _to_str(self, *args, **kwargs):
  53. data = copy.deepcopy(self)
  54. data.pop("input_img")
  55. data["pred"] = "..."
  56. return JsonMixin._to_str(data, *args, **kwargs)
  57. def _to_json(self, *args, **kwargs):
  58. data = copy.deepcopy(self)
  59. data.pop("input_img")
  60. return JsonMixin._to_json(data, *args, **kwargs)