instance_seg.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 PIL
  18. from PIL import Image, ImageDraw, ImageFont
  19. from ...utils import logging
  20. from ...utils.fonts import PINGFANG_FONT_FILE_PATH
  21. from ..utils.io import ImageWriter, ImageReader
  22. from ..utils.color_map import get_color_map_list, font_colormap
  23. from .base import BaseResult
  24. from .det import draw_box
  25. def draw_mask(im, np_boxes, np_masks, labels):
  26. """
  27. Args:
  28. im (PIL.Image.Image): PIL image
  29. np_boxes (np.ndarray): shape:[N,6], N: number of box,
  30. matix element:[class, score, x_min, y_min, x_max, y_max]
  31. np_masks (np.ndarray): shape:[N, im_h, im_w]
  32. labels (list): labels:['class1', ..., 'classn']
  33. Returns:
  34. im (PIL.Image.Image): visualized image
  35. """
  36. color_list = get_color_map_list(len(labels))
  37. w_ratio = 0.4
  38. alpha = 0.7
  39. im = np.array(im).astype("float32")
  40. clsid2color = {}
  41. im_h, im_w = im.shape[:2]
  42. np_masks = np_masks[:, :im_h, :im_w]
  43. for i in range(len(np_masks)):
  44. clsid, score = int(np_boxes[i][0]), np_boxes[i][1]
  45. mask = np_masks[i]
  46. if clsid not in clsid2color:
  47. clsid2color[clsid] = color_list[clsid]
  48. color_mask = clsid2color[clsid]
  49. for c in range(3):
  50. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  51. idx = np.nonzero(mask)
  52. color_mask = np.array(color_mask)
  53. im[idx[0], idx[1], :] *= 1.0 - alpha
  54. im[idx[0], idx[1], :] += alpha * color_mask
  55. return Image.fromarray(im.astype("uint8"))
  56. class InstanceSegResults(BaseResult):
  57. """Save Result Transform"""
  58. def __init__(self, data):
  59. super().__init__(data)
  60. self.data = data
  61. # We use pillow backend to save both numpy arrays and PIL Image objects
  62. self._img_reader.set_backend("pillow")
  63. self._img_writer.set_backend("pillow")
  64. def _get_res_img(self):
  65. """apply"""
  66. boxes = self["boxes"]
  67. masks = self["masks"]
  68. img_path = self["img_path"]
  69. labels = self.data["labels"]
  70. file_name = os.path.basename(img_path)
  71. image = self._img_reader.read(img_path)
  72. image = draw_mask(image, boxes, masks, labels)
  73. image = draw_box(image, boxes, labels=labels)
  74. self["boxes"] = boxes.tolist()
  75. self["masks"] = masks.tolist()
  76. return image