-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdraw_yolo_boxes.py
90 lines (70 loc) · 2.7 KB
/
draw_yolo_boxes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import argparse
import sys
import glob
import os
from PIL import Image, ImageDraw
def main():
parser = argparse.ArgumentParser(description="Draw YOLO boxes to images")
parser.add_argument(
"input",
type=str,
help="Path to image or directory from yolo dataset"
)
args = parser.parse_args()
images = []
annotations = []
annotations_path = None
if os.path.isfile(args.input):
images = [args.input]
annotations_path = os.path.join(os.path.dirname(args.input), "..", "labels")
elif os.path.isdir(args.input):
for ext in ["jpg", "tif", "png", "jpeg", "tiff"]:
p = os.path.join(args.input, "images")
images += glob.glob(f"{p}/*.{ext}")
annotations_path = os.path.join(args.input, "labels")
if not os.path.isdir(annotations_path):
print(f"Cannot find annotations directory: {annotations_path}")
exit(1)
print(f"Found {len(images)} images")
pairs = []
for im in images:
p, ext = os.path.splitext(im)
ann_file = os.path.join(annotations_path, os.path.basename(p) + ".txt")
if os.path.isfile(ann_file):
pairs += [(im, ann_file)]
else:
print(f"Cannot find {ann_file}")
if len(pairs) == len(images):
print("All annotations match")
else:
print(f"Skipped {len(images) - len(pairs)} images")
output_dir = os.path.abspath(os.path.join(annotations_path, "..", "draw_output"))
os.makedirs(output_dir, exist_ok=True)
for im,ann in pairs:
img = Image.open(im).convert("RGB")
draw = ImageDraw.Draw(img)
color = (255, 0, 0) # Red for the bounding box
boxes = []
classes = []
with open(ann, "r") as f:
lines = [p for p in f.read().strip().split("\n") if p != ""]
for line in lines:
parts = line.split(" ")
if len(parts) != 5:
print(f"Invalid format: {os.path.basename(ann)}: {line}")
continue
classes.append(int(parts[0]))
boxes.append([float(p) for p in parts[1:]])
# Draw bounding boxes with scores
for b, cla in zip(boxes, classes):
x, y, w, h = b
x1 = (x - w / 2) * img.width
y1 = (y - h / 2) * img.height
x2 = (x + w / 2) * img.width
y2 = (y + h / 2) * img.height
draw.rectangle([x1, y1, x2, y2], outline=color, width=4)
draw.text((x1, y1 - 10), str(cla), fill=color)
img.save(os.path.join(output_dir, os.path.basename(im)))
print(f"Wrote images to {output_dir}")
if __name__ == "__main__":
main()