instance_seg.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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 os
  15. import numpy as np
  16. import math
  17. import copy
  18. import json
  19. import cv2
  20. import PIL
  21. from PIL import Image, ImageDraw, ImageFont
  22. from ...utils import logging
  23. from ...utils.fonts import PINGFANG_FONT_FILE_PATH
  24. from ..utils.io import ImageWriter, ImageReader
  25. from ..utils.color_map import get_colormap, font_colormap
  26. from .base import BaseResult
  27. from .det import draw_box
  28. def draw_segm(im, masks, mask_info, alpha=0.7):
  29. """
  30. Draw segmentation on image
  31. """
  32. mask_color_id = 0
  33. w_ratio = 0.4
  34. color_list = get_colormap(rgb=True)
  35. im = np.array(im).astype("float32")
  36. clsid2color = {}
  37. masks = np.array(masks)
  38. masks = masks.astype(np.uint8)
  39. for i in range(masks.shape[0]):
  40. mask, score, clsid = masks[i], mask_info[i]["score"], mask_info[i]["class_id"]
  41. if clsid not in clsid2color:
  42. color_index = i % len(color_list)
  43. clsid2color[clsid] = color_list[color_index]
  44. color_mask = clsid2color[clsid]
  45. for c in range(3):
  46. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  47. idx = np.nonzero(mask)
  48. color_mask = np.array(color_mask)
  49. idx0 = np.minimum(idx[0], im.shape[0] - 1)
  50. idx1 = np.minimum(idx[1], im.shape[1] - 1)
  51. im[idx0, idx1, :] *= 1.0 - alpha
  52. im[idx0, idx1, :] += alpha * color_mask
  53. sum_x = np.sum(mask, axis=0)
  54. x = np.where(sum_x > 0.5)[0]
  55. sum_y = np.sum(mask, axis=1)
  56. y = np.where(sum_y > 0.5)[0]
  57. x0, x1, y0, y1 = x[0], x[-1], y[0], y[-1]
  58. cv2.rectangle(
  59. im, (x0, y0), (x1, y1), tuple(color_mask.astype("int32").tolist()), 1
  60. )
  61. bbox_text = "%s %.2f" % (mask_info[i]["label"], score)
  62. t_size = cv2.getTextSize(bbox_text, 0, 0.3, thickness=1)[0]
  63. cv2.rectangle(
  64. im,
  65. (x0, y0),
  66. (x0 + t_size[0], y0 - t_size[1] - 3),
  67. tuple(color_mask.astype("int32").tolist()),
  68. -1,
  69. )
  70. cv2.putText(
  71. im,
  72. bbox_text,
  73. (x0, y0 - 2),
  74. cv2.FONT_HERSHEY_SIMPLEX,
  75. 0.3,
  76. (0, 0, 0),
  77. 1,
  78. lineType=cv2.LINE_AA,
  79. )
  80. return Image.fromarray(im.astype("uint8"))
  81. def restore_to_draw_masks(img_size, boxes, masks):
  82. """
  83. Restores extracted masks to the original shape and draws them on a blank image.
  84. """
  85. restored_masks = []
  86. for i, (box, mask) in enumerate(zip(boxes, masks)):
  87. restored_mask = np.zeros(img_size, dtype=np.uint8)
  88. x_min, y_min, x_max, y_max = map(lambda x: int(round(x)), box["coordinate"])
  89. restored_mask[y_min:y_max, x_min:x_max] = mask
  90. restored_masks.append(restored_mask)
  91. return np.array(restored_masks)
  92. def draw_mask(im, boxes, np_masks, img_size):
  93. """
  94. Args:
  95. im (PIL.Image.Image): PIL image
  96. boxes (list): a list of dictionaries representing detection box information.
  97. np_masks (np.ndarray): shape:[N, im_h, im_w]
  98. Returns:
  99. im (PIL.Image.Image): visualized image
  100. """
  101. color_list = get_colormap(rgb=True)
  102. w_ratio = 0.4
  103. alpha = 0.7
  104. im = np.array(im).astype("float32")
  105. clsid2color = {}
  106. np_masks = restore_to_draw_masks(img_size, boxes, np_masks)
  107. im_h, im_w = im.shape[:2]
  108. np_masks = np_masks[:, :im_h, :im_w]
  109. for i in range(len(np_masks)):
  110. clsid, score = int(boxes[i]["cls_id"]), boxes[i]["score"]
  111. mask = np_masks[i]
  112. if clsid not in clsid2color:
  113. color_index = i % len(color_list)
  114. clsid2color[clsid] = color_list[color_index]
  115. color_mask = clsid2color[clsid]
  116. for c in range(3):
  117. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  118. idx = np.nonzero(mask)
  119. color_mask = np.array(color_mask)
  120. im[idx[0], idx[1], :] *= 1.0 - alpha
  121. im[idx[0], idx[1], :] += alpha * color_mask
  122. return Image.fromarray(im.astype("uint8"))
  123. class InstanceSegResult(BaseResult):
  124. """Save Result Transform"""
  125. def __init__(self, data):
  126. super().__init__(data)
  127. # We use pillow backend to save both numpy arrays and PIL Image objects
  128. self._img_reader.set_backend("pillow")
  129. self._img_writer.set_backend("pillow")
  130. def _get_res_img(self):
  131. """apply"""
  132. img_path = self["img_path"]
  133. file_name = os.path.basename(img_path)
  134. image = self._img_reader.read(img_path)
  135. ori_img_size = list(image.size)[::-1]
  136. boxes = self["boxes"]
  137. masks = self["masks"]
  138. if next((True for item in self["boxes"] if "coordinate" in item), False):
  139. image = draw_mask(image, boxes, masks, ori_img_size)
  140. image = draw_box(image, boxes)
  141. else:
  142. image = draw_segm(image, masks, boxes)
  143. return image
  144. def print(self, json_format=True, indent=4, ensure_ascii=False):
  145. str_ = copy.deepcopy(self)
  146. del str_["masks"]
  147. if json_format:
  148. str_ = json.dumps(str_, indent=indent, ensure_ascii=ensure_ascii)
  149. logging.info(str_)