visualizer.py 5.7 KB

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