result.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 ....utils.deps import function_requires_deps, is_dep_available
  18. from ...common.result import BaseCVResult, JsonMixin
  19. from ...utils.color_map import get_colormap
  20. from ..object_detection.result import draw_box
  21. if is_dep_available("opencv-contrib-python"):
  22. import cv2
  23. @function_requires_deps("opencv-contrib-python")
  24. def draw_segm(im, masks, mask_info, alpha=0.7):
  25. """
  26. Draw segmentation on image
  27. """
  28. w_ratio = 0.4
  29. color_list = get_colormap(rgb=True)
  30. im = np.array(im).astype("float32")
  31. clsid2color = {}
  32. masks = np.array(masks)
  33. masks = masks.astype(np.uint8)
  34. for i in range(masks.shape[0]):
  35. mask, score, clsid = masks[i], mask_info[i]["score"], mask_info[i]["class_id"]
  36. if clsid not in clsid2color:
  37. color_index = i % len(color_list)
  38. clsid2color[clsid] = color_list[color_index]
  39. color_mask = clsid2color[clsid]
  40. for c in range(3):
  41. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  42. idx = np.nonzero(mask)
  43. color_mask = np.array(color_mask)
  44. idx0 = np.minimum(idx[0], im.shape[0] - 1)
  45. idx1 = np.minimum(idx[1], im.shape[1] - 1)
  46. im[idx0, idx1, :] *= 1.0 - alpha
  47. im[idx0, idx1, :] += alpha * color_mask
  48. sum_x = np.sum(mask, axis=0)
  49. x = np.where(sum_x > 0.5)[0]
  50. sum_y = np.sum(mask, axis=1)
  51. y = np.where(sum_y > 0.5)[0]
  52. x0, x1, y0, y1 = x[0], x[-1], y[0], y[-1]
  53. cv2.rectangle(
  54. im, (x0, y0), (x1, y1), tuple(color_mask.astype("int32").tolist()), 1
  55. )
  56. bbox_text = "%s %.2f" % (mask_info[i]["label"], score)
  57. t_size = cv2.getTextSize(bbox_text, 0, 0.3, thickness=1)[0]
  58. cv2.rectangle(
  59. im,
  60. (x0, y0),
  61. (x0 + t_size[0], y0 - t_size[1] - 3),
  62. tuple(color_mask.astype("int32").tolist()),
  63. -1,
  64. )
  65. cv2.putText(
  66. im,
  67. bbox_text,
  68. (x0, y0 - 2),
  69. cv2.FONT_HERSHEY_SIMPLEX,
  70. 0.3,
  71. (0, 0, 0),
  72. 1,
  73. lineType=cv2.LINE_AA,
  74. )
  75. return Image.fromarray(im.astype("uint8"))
  76. def restore_to_draw_masks(img_size, boxes, masks):
  77. """
  78. Restores extracted masks to the original shape and draws them on a blank image.
  79. """
  80. restored_masks = []
  81. for i, (box, mask) in enumerate(zip(boxes, masks)):
  82. restored_mask = np.zeros(img_size, dtype=np.uint8)
  83. x_min, y_min, x_max, y_max = map(lambda x: int(round(x)), box["coordinate"])
  84. restored_mask[y_min:y_max, x_min:x_max] = mask
  85. restored_masks.append(restored_mask)
  86. return np.array(restored_masks)
  87. def draw_mask(im, boxes, np_masks, img_size):
  88. """
  89. Args:
  90. im (PIL.Image.Image): PIL image
  91. boxes (list): a list of dictionaries representing detection box information.
  92. np_masks (np.ndarray): shape:[N, im_h, im_w]
  93. Returns:
  94. im (PIL.Image.Image): visualized image
  95. """
  96. color_list = get_colormap(rgb=True)
  97. w_ratio = 0.4
  98. alpha = 0.7
  99. im = np.array(im).astype("float32")
  100. clsid2color = {}
  101. np_masks = restore_to_draw_masks(img_size, boxes, np_masks)
  102. im_h, im_w = im.shape[:2]
  103. np_masks = np_masks[:, :im_h, :im_w]
  104. for i in range(len(np_masks)):
  105. clsid, score = int(boxes[i]["cls_id"]), boxes[i]["score"]
  106. mask = np_masks[i]
  107. if clsid not in clsid2color:
  108. color_index = i % len(color_list)
  109. clsid2color[clsid] = color_list[color_index]
  110. color_mask = clsid2color[clsid]
  111. for c in range(3):
  112. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  113. idx = np.nonzero(mask)
  114. color_mask = np.array(color_mask)
  115. im[idx[0], idx[1], :] *= 1.0 - alpha
  116. im[idx[0], idx[1], :] += alpha * color_mask
  117. return Image.fromarray(im.astype("uint8"))
  118. class InstanceSegResult(BaseCVResult):
  119. """Save Result Transform"""
  120. def _to_img(self):
  121. """apply"""
  122. # image = self._img_reader.read(self["input_path"])
  123. image = Image.fromarray(self["input_img"])
  124. ori_img_size = list(image.size)[::-1]
  125. boxes = self["boxes"]
  126. masks = self["masks"]
  127. if next((True for item in self["boxes"] if "coordinate" in item), False):
  128. image = draw_mask(image, boxes, masks, ori_img_size)
  129. image = draw_box(image, boxes)
  130. else:
  131. image = draw_segm(image, masks, boxes)
  132. return {"res": image}
  133. def _to_str(self, *args, **kwargs):
  134. data = copy.deepcopy(self)
  135. data.pop("input_img")
  136. data["masks"] = "..."
  137. return JsonMixin._to_str(data, *args, **kwargs)
  138. def _to_json(self, *args, **kwargs):
  139. data = copy.deepcopy(self)
  140. data.pop("input_img")
  141. return JsonMixin._to_json(data, *args, **kwargs)