visualizer.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 cv2
  15. import numpy as np
  16. def get_color_map_list(length):
  17. """Returns the color map for visualizing the segmentation mask"""
  18. length += 1
  19. color_map = length * [0, 0, 0]
  20. for i in range(0, length):
  21. j = 0
  22. lab = i
  23. while lab:
  24. color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
  25. color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
  26. color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
  27. j += 1
  28. lab >>= 3
  29. color_map = color_map[3:]
  30. return color_map
  31. def visualize(image, result, weight=0.6, use_multilabel=False):
  32. """ Convert predict result to color image, and save added image. """
  33. color_map = get_color_map_list(256)
  34. color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
  35. color_map = np.array(color_map).astype("uint8")
  36. if not use_multilabel:
  37. # Use OpenCV LUT for color mapping
  38. c1 = cv2.LUT(result, color_map[:, 0])
  39. c2 = cv2.LUT(result, color_map[:, 1])
  40. c3 = cv2.LUT(result, color_map[:, 2])
  41. pseudo_img = np.dstack((c3, c2, c1))
  42. vis_result = cv2.addWeighted(image, weight, pseudo_img, 1 - weight, 0)
  43. else:
  44. vis_result = image.copy()
  45. for i in range(result.shape[0]):
  46. mask = result[i]
  47. c1 = np.where(mask, color_map[i, 0], vis_result[..., 0])
  48. c2 = np.where(mask, color_map[i, 1], vis_result[..., 1])
  49. c3 = np.where(mask, color_map[i, 2], vis_result[..., 2])
  50. pseudo_img = np.dstack((c3, c2, c1)).astype('uint8')
  51. contour, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL,
  52. cv2.CHAIN_APPROX_SIMPLE)
  53. vis_result = cv2.addWeighted(vis_result, weight, pseudo_img,
  54. 1 - weight, 0)
  55. contour_color = (int(color_map[i, 0]), int(color_map[i, 1]),
  56. int(color_map[i, 2]))
  57. vis_result = cv2.drawContours(vis_result, contour, -1,
  58. contour_color, 1)
  59. return vis_result