henry000 commited on
Commit
2c1f270
·
1 Parent(s): 7692528

🎨 [Update] drawer

Browse files
Files changed (1) hide show
  1. yolo/tools/drawer.py +24 -6
yolo/tools/drawer.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
- from typing import List, Union
 
3
 
4
  import numpy as np
5
  import torch
@@ -15,6 +16,7 @@ def draw_bboxes(
15
  scaled_bbox: bool = True,
16
  save_path: str = "",
17
  save_name: str = "visualize.png",
 
18
  ):
19
  """
20
  Draw bounding boxes on an image.
@@ -32,20 +34,36 @@ def draw_bboxes(
32
  bboxes = bboxes[0]
33
  img = to_pil_image(img)
34
 
35
- draw = ImageDraw.Draw(img)
36
  width, height = img.size
37
- font = ImageFont.load_default(30)
 
 
 
38
 
39
  for bbox in bboxes:
40
- class_id, x_min, y_min, x_max, y_max, *conf = bbox
41
  if scaled_bbox:
42
  x_min = x_min * width
43
  x_max = x_max * width
44
  y_min = y_min * height
45
  y_max = y_max * height
46
  shape = [(x_min, y_min), (x_max, y_max)]
47
- draw.rectangle(shape, outline="red", width=3)
48
- draw.text((x_min, y_min), str(int(class_id)), font=font, fill="blue")
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  save_image_path = os.path.join(save_path, save_name)
51
  img.save(save_image_path) # Save the image with annotations
 
1
  import os
2
+ import random
3
+ from typing import List, Optional, Union
4
 
5
  import numpy as np
6
  import torch
 
16
  scaled_bbox: bool = True,
17
  save_path: str = "",
18
  save_name: str = "visualize.png",
19
+ idx2label: Optional[list],
20
  ):
21
  """
22
  Draw bounding boxes on an image.
 
34
  bboxes = bboxes[0]
35
  img = to_pil_image(img)
36
 
37
+ draw = ImageDraw.Draw(img, "RGBA")
38
  width, height = img.size
39
+ try:
40
+ font = ImageFont.truetype("arial.ttf", 15)
41
+ except IOError:
42
+ font = ImageFont.load_default()
43
 
44
  for bbox in bboxes:
45
+ class_id, x_min, y_min, x_max, y_max, *conf = [float(val) for val in bbox]
46
  if scaled_bbox:
47
  x_min = x_min * width
48
  x_max = x_max * width
49
  y_min = y_min * height
50
  y_max = y_max * height
51
  shape = [(x_min, y_min), (x_max, y_max)]
52
+ random.seed(int(class_id))
53
+ color_map = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
54
+ draw.rounded_rectangle(shape, outline=(*color_map, 170), radius=5)
55
+ draw.rounded_rectangle(shape, fill=(*color_map, 50), radius=5)
56
+
57
+ text_class = str(idx2label[int(class_id)] if idx2label else class_id)
58
+ label_text = f"{text_class}" + (f" {conf[0]: .0%}" if conf else "")
59
+
60
+ text_bbox = font.getbbox(label_text)
61
+ text_width = text_bbox[2] - text_bbox[0]
62
+ text_height = (text_bbox[3] - text_bbox[1]) * 1.25
63
+
64
+ text_background = [(x_min, y_min), (x_min + text_width, y_min + text_height)]
65
+ draw.rounded_rectangle(text_background, fill=(*color_map, 175), radius=2)
66
+ draw.text((x_min, y_min), label_text, fill="white", font=font)
67
 
68
  save_image_path = os.path.join(save_path, save_name)
69
  img.save(save_image_path) # Save the image with annotations