visualizer.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. [
  31. 0xFF,
  32. 0x00,
  33. 0x00,
  34. 0xCC,
  35. 0xFF,
  36. 0x00,
  37. 0x00,
  38. 0xFF,
  39. 0x66,
  40. 0x00,
  41. 0x66,
  42. 0xFF,
  43. 0xCC,
  44. 0x00,
  45. 0xFF,
  46. 0xFF,
  47. 0x4D,
  48. 0x00,
  49. 0x80,
  50. 0xFF,
  51. 0x00,
  52. 0x00,
  53. 0xFF,
  54. 0xB2,
  55. 0x00,
  56. 0x1A,
  57. 0xFF,
  58. 0xFF,
  59. 0x00,
  60. 0xE5,
  61. 0xFF,
  62. 0x99,
  63. 0x00,
  64. 0x33,
  65. 0xFF,
  66. 0x00,
  67. 0x00,
  68. 0xFF,
  69. 0xFF,
  70. 0x33,
  71. 0x00,
  72. 0xFF,
  73. 0xFF,
  74. 0x00,
  75. 0x99,
  76. 0xFF,
  77. 0xE5,
  78. 0x00,
  79. 0x00,
  80. 0xFF,
  81. 0x1A,
  82. 0x00,
  83. 0xB2,
  84. 0xFF,
  85. 0x80,
  86. 0x00,
  87. 0xFF,
  88. 0xFF,
  89. 0x00,
  90. 0x4D,
  91. ]
  92. ).astype(np.float32)
  93. color_list = color_list.reshape((-1, 3))
  94. if not rgb:
  95. color_list = color_list[:, ::-1]
  96. return color_list.astype("int32")
  97. def font_colormap(color_index):
  98. """
  99. Get font color according to the index of colormap
  100. """
  101. dark = np.array([0x14, 0x0E, 0x35])
  102. light = np.array([0xFF, 0xFF, 0xFF])
  103. light_indexs = [0, 3, 4, 8, 9, 13, 14, 18, 19]
  104. if color_index in light_indexs:
  105. return light.astype("int32")
  106. else:
  107. return dark.astype("int32")
  108. def draw_bbox(image, coco_info: COCO, img_id):
  109. """
  110. Draw bbox on image
  111. """
  112. try:
  113. image_info = coco_info.loadImgs(img_id)[0]
  114. font_size = int(0.024 * int(image_info["width"])) + 2
  115. except:
  116. font_size = 12
  117. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8")
  118. image = image.convert("RGB")
  119. draw = ImageDraw.Draw(image)
  120. image_size = image.size
  121. width = int(max(image_size) * 0.005)
  122. catid2color = {}
  123. catid2fontcolor = {}
  124. catid_num_dict = {}
  125. color_list = colormap(rgb=True)
  126. annotations = coco_info.loadAnns(coco_info.getAnnIds(imgIds=img_id))
  127. for ann in annotations:
  128. catid = ann["category_id"]
  129. catid_num_dict[catid] = catid_num_dict.get(catid, 0) + 1
  130. for i, (catid, _) in enumerate(
  131. sorted(catid_num_dict.items(), key=lambda x: x[1], reverse=True)
  132. ):
  133. if catid not in catid2color:
  134. color_index = i % len(color_list)
  135. catid2color[catid] = color_list[color_index]
  136. catid2fontcolor[catid] = font_colormap(color_index)
  137. for ann in annotations:
  138. catid, bbox = ann["category_id"], ann["bbox"]
  139. color = tuple(catid2color[catid])
  140. font_color = tuple(catid2fontcolor[catid])
  141. if len(bbox) == 4:
  142. # draw bbox
  143. xmin, ymin, w, h = bbox
  144. xmax = xmin + w
  145. ymax = ymin + h
  146. draw.line(
  147. [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin)],
  148. width=width,
  149. fill=color,
  150. )
  151. elif len(bbox) == 8:
  152. x1, y1, x2, y2, x3, y3, x4, y4 = bbox
  153. draw.line(
  154. [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)],
  155. width=width,
  156. fill=color,
  157. )
  158. xmin = min(x1, x2, x3, x4)
  159. ymin = min(y1, y2, y3, y4)
  160. else:
  161. logging.info("Error: The shape of bbox must be [M, 4] or [M, 8]!")
  162. # draw label
  163. label = coco_info.loadCats(catid)[0]["name"]
  164. text = "{}".format(label)
  165. if tuple(map(int, PIL.__version__.split("."))) <= (10, 0, 0):
  166. tw, th = draw.textsize(text, font=font)
  167. else:
  168. left, top, right, bottom = draw.textbbox((0, 0), text, font)
  169. tw, th = right - left, bottom - top
  170. if ymin < th:
  171. draw.rectangle([(xmin, ymin), (xmin + tw + 4, ymin + th + 1)], fill=color)
  172. draw.text((xmin + 2, ymin - 2), text, fill=font_color, font=font)
  173. else:
  174. draw.rectangle([(xmin, ymin - th), (xmin + tw + 4, ymin + 1)], fill=color)
  175. draw.text((xmin + 2, ymin - th - 2), text, fill=font_color, font=font)
  176. return image