visualizer.py 2.8 KB

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