instance_seg.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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 PIL
  20. from PIL import Image, ImageDraw, ImageFont
  21. from ...utils import logging
  22. from ...utils.fonts import PINGFANG_FONT_FILE_PATH
  23. from ..utils.io import ImageWriter, ImageReader
  24. from ..utils.color_map import get_colormap, font_colormap
  25. from .base import BaseResult
  26. from .det import draw_box
  27. def restore_to_draw_masks(img_size, boxes, masks):
  28. """
  29. Restores extracted masks to the original shape and draws them on a blank image.
  30. """
  31. restored_masks = []
  32. for i, (box, mask) in enumerate(zip(boxes, masks)):
  33. restored_mask = np.zeros(img_size, dtype=np.uint8)
  34. x_min, y_min, x_max, y_max = map(lambda x: int(round(x)), box["coordinate"])
  35. restored_mask[y_min:y_max, x_min:x_max] = mask
  36. restored_masks.append(restored_mask)
  37. return np.array(restored_masks)
  38. def draw_mask(im, boxes, np_masks, img_size):
  39. """
  40. Args:
  41. im (PIL.Image.Image): PIL image
  42. boxes (list): a list of dictionaries representing detection box information.
  43. np_masks (np.ndarray): shape:[N, im_h, im_w]
  44. Returns:
  45. im (PIL.Image.Image): visualized image
  46. """
  47. color_list = get_colormap(rgb=True)
  48. w_ratio = 0.4
  49. alpha = 0.7
  50. im = np.array(im).astype("float32")
  51. clsid2color = {}
  52. np_masks = restore_to_draw_masks(img_size, boxes, np_masks)
  53. im_h, im_w = im.shape[:2]
  54. np_masks = np_masks[:, :im_h, :im_w]
  55. for i in range(len(np_masks)):
  56. clsid, score = int(boxes[i]["cls_id"]), boxes[i]["score"]
  57. mask = np_masks[i]
  58. if clsid not in clsid2color:
  59. color_index = i % len(color_list)
  60. clsid2color[clsid] = color_list[color_index]
  61. color_mask = clsid2color[clsid]
  62. for c in range(3):
  63. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  64. idx = np.nonzero(mask)
  65. color_mask = np.array(color_mask)
  66. im[idx[0], idx[1], :] *= 1.0 - alpha
  67. im[idx[0], idx[1], :] += alpha * color_mask
  68. return Image.fromarray(im.astype("uint8"))
  69. class InstanceSegResult(BaseResult):
  70. """Save Result Transform"""
  71. def __init__(self, data):
  72. super().__init__(data)
  73. # We use pillow backend to save both numpy arrays and PIL Image objects
  74. self._img_reader.set_backend("pillow")
  75. self._img_writer.set_backend("pillow")
  76. def _get_res_img(self):
  77. """apply"""
  78. boxes = np.array(self["boxes"])
  79. masks = self["masks"]
  80. img_path = self["img_path"]
  81. file_name = os.path.basename(img_path)
  82. image = self._img_reader.read(img_path)
  83. ori_img_size = list(image.size)[::-1]
  84. image = draw_mask(image, boxes, masks, ori_img_size)
  85. image = draw_box(image, boxes)
  86. return image
  87. def print(self, json_format=True, indent=4, ensure_ascii=False):
  88. str_ = copy.deepcopy(self)
  89. del str_["masks"]
  90. if json_format:
  91. str_ = json.dumps(str_, indent=indent, ensure_ascii=ensure_ascii)
  92. logging.info(str_)