visualizer.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 json
  17. from pathlib import Path
  18. from PIL import Image, ImageDraw, ImageFont
  19. from pycocotools.coco import COCO
  20. from ......utils.fonts import PINGFANG_FONT_FILE_PATH
  21. from ......utils import logging
  22. def colormap(rgb=False):
  23. """
  24. Get colormap
  25. The code of this function is copied from https://github.com/facebookresearch/Detectron/blob/main/detectron/\
  26. utils/colormap.py
  27. """
  28. color_list = np.array([
  29. 0xFF, 0x00, 0x00, 0xCC, 0xFF, 0x00, 0x00, 0xFF, 0x66, 0x00, 0x66, 0xFF,
  30. 0xCC, 0x00, 0xFF, 0xFF, 0x4D, 0x00, 0x80, 0xff, 0x00, 0x00, 0xFF, 0xB2,
  31. 0x00, 0x1A, 0xFF, 0xFF, 0x00, 0xE5, 0xFF, 0x99, 0x00, 0x33, 0xFF, 0x00,
  32. 0x00, 0xFF, 0xFF, 0x33, 0x00, 0xFF, 0xff, 0x00, 0x99, 0xFF, 0xE5, 0x00,
  33. 0x00, 0xFF, 0x1A, 0x00, 0xB2, 0xFF, 0x80, 0x00, 0xFF, 0xFF, 0x00, 0x4D
  34. ]).astype(np.float32)
  35. color_list = (color_list.reshape((-1, 3)))
  36. if not rgb:
  37. color_list = color_list[:, ::-1]
  38. return color_list.astype('int32')
  39. def font_colormap(color_index):
  40. """
  41. Get font color according to the index of colormap
  42. """
  43. dark = np.array([0x14, 0x0E, 0x35])
  44. light = np.array([0xFF, 0xFF, 0xFF])
  45. light_indexs = [0, 3, 4, 8, 9, 13, 14, 18, 19]
  46. if color_index in light_indexs:
  47. return light.astype('int32')
  48. else:
  49. return dark.astype('int32')
  50. def draw_bbox(image, coco_info: COCO, img_id):
  51. """
  52. Draw bbox on image
  53. """
  54. try:
  55. image_info = coco_info.loadImgs(img_id)[0]
  56. font_size = int(0.024 * int(image_info['width'])) + 2
  57. except:
  58. font_size = 12
  59. font = ImageFont.truetype(
  60. PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8")
  61. image = image.convert('RGB')
  62. draw = ImageDraw.Draw(image)
  63. image_size = image.size
  64. width = int(max(image_size) * 0.005)
  65. catid2color = {}
  66. catid2fontcolor = {}
  67. catid_num_dict = {}
  68. color_list = colormap(rgb=True)
  69. annotations = coco_info.loadAnns(coco_info.getAnnIds(imgIds=img_id))
  70. for ann in annotations:
  71. catid = ann['category_id']
  72. catid_num_dict[catid] = catid_num_dict.get(catid, 0) + 1
  73. for i, (catid, _) in enumerate(
  74. sorted(
  75. catid_num_dict.items(), key=lambda x: x[1], reverse=True)):
  76. if catid not in catid2color:
  77. color_index = i % len(color_list)
  78. catid2color[catid] = color_list[color_index]
  79. catid2fontcolor[catid] = font_colormap(color_index)
  80. for ann in annotations:
  81. catid, bbox = ann['category_id'], ann['bbox']
  82. color = tuple(catid2color[catid])
  83. font_color = tuple(catid2fontcolor[catid])
  84. if len(bbox) == 4:
  85. # draw bbox
  86. xmin, ymin, w, h = bbox
  87. xmax = xmin + w
  88. ymax = ymin + h
  89. draw.line(
  90. [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin),
  91. (xmin, ymin)],
  92. width=width,
  93. fill=color)
  94. elif len(bbox) == 8:
  95. x1, y1, x2, y2, x3, y3, x4, y4 = bbox
  96. draw.line(
  97. [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)],
  98. width=width,
  99. fill=color)
  100. xmin = min(x1, x2, x3, x4)
  101. ymin = min(y1, y2, y3, y4)
  102. else:
  103. logging.info('Error: The shape of bbox must be [M, 4] or [M, 8]!')
  104. # draw label
  105. label = coco_info.loadCats(catid)[0]['name']
  106. text = "{}".format(label)
  107. tw, th = draw.textsize(text, font=font)
  108. if ymin < th:
  109. draw.rectangle(
  110. [(xmin, ymin), (xmin + tw + 4, ymin + th + 1)], fill=color)
  111. draw.text((xmin + 2, ymin - 2), text, fill=font_color, font=font)
  112. else:
  113. draw.rectangle(
  114. [(xmin, ymin - th), (xmin + tw + 4, ymin + 1)], fill=color)
  115. draw.text(
  116. (xmin + 2, ymin - th - 2), text, fill=font_color, font=font)
  117. return image
  118. def draw_mask(image, coco_info: COCO, img_id):
  119. """
  120. Draw mask on image
  121. """
  122. mask_color_id = 0
  123. w_ratio = .4
  124. alpha = 0.6
  125. color_list = colormap(rgb=True)
  126. img_array = np.array(image).astype('float32')
  127. h, w = img_array.shape[:2]
  128. annotations = coco_info.loadAnns(coco_info.getAnnIds(imgIds=img_id))
  129. for ann in annotations:
  130. segm = ann['segmentation']
  131. if not segm:
  132. continue
  133. import pycocotools.mask as mask_util
  134. rles = mask_util.frPyObjects(segm, h, w)
  135. rle = mask_util.merge(rles)
  136. mask = mask_util.decode(rle) * 255
  137. color_mask = color_list[mask_color_id % len(color_list), 0:3]
  138. mask_color_id += 1
  139. for c in range(3):
  140. color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio * 255
  141. idx = np.nonzero(mask)
  142. img_array[idx[0], idx[1], :] *= 1.0 - alpha
  143. img_array[idx[0], idx[1], :] += alpha * color_mask
  144. return Image.fromarray(img_array.astype('uint8'))