TSAnnotate 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- TSAnnotate/Annotate.py +38 -0
- TSAnnotate/Export.py +146 -0
- TSAnnotate/Filter.py +20 -0
- TSAnnotate/Load.py +109 -0
- TSAnnotate/Main.py +128 -0
- TSAnnotate/Sample.py +19 -0
- TSAnnotate/__init__.py +0 -0
- TSAnnotate/data/labels.csv +171 -0
- tsannotate-1.0.0.dist-info/._entry_points.txt +0 -0
- tsannotate-1.0.0.dist-info/._requires.txt +0 -0
- tsannotate-1.0.0.dist-info/._top_level.txt +0 -0
- tsannotate-1.0.0.dist-info/METADATA +216 -0
- tsannotate-1.0.0.dist-info/RECORD +17 -0
- tsannotate-1.0.0.dist-info/WHEEL +5 -0
- tsannotate-1.0.0.dist-info/entry_points.txt +2 -0
- tsannotate-1.0.0.dist-info/licenses/LICENSE +21 -0
- tsannotate-1.0.0.dist-info/top_level.txt +1 -0
TSAnnotate/Annotate.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from TSAnnotate.Load import load_labels, load_model
|
|
3
|
+
from torchvision.transforms.v2.functional import to_image
|
|
4
|
+
from torchvision.transforms.v2 import Compose, Pad, Resize, ToDtype
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def annotate(image, labels_path=None, model_path=None):
|
|
8
|
+
labels = load_labels(labels_path)
|
|
9
|
+
model = load_model(model_path)
|
|
10
|
+
image_tensor = to_image(image)
|
|
11
|
+
# pad image to square and scale to target size
|
|
12
|
+
width = image_tensor.size(-1)
|
|
13
|
+
height = image_tensor.size(-2)
|
|
14
|
+
longer_edge = max(width, height)
|
|
15
|
+
pad_width = int(longer_edge - width)
|
|
16
|
+
pad_height = int(longer_edge - height)
|
|
17
|
+
pad_transform = Compose([Pad([pad_width, pad_height, 0, 0]), Resize([640, 640]), ToDtype(torch.float)])
|
|
18
|
+
padded_image = torch.unsqueeze(pad_transform(image_tensor), 0) / 255
|
|
19
|
+
# apply model
|
|
20
|
+
prediction = model(padded_image, verbose=False)
|
|
21
|
+
# convert box coordinates for original image
|
|
22
|
+
boxes = prediction[0].boxes.data[:, 0:4] * (longer_edge / 640)
|
|
23
|
+
boxes[:, 0] = torch.round(((boxes[:, 0] - pad_width) / width) * 100, decimals=2)
|
|
24
|
+
boxes[:, 1] = torch.round(((boxes[:, 1] - pad_height) / height) * 100, decimals=2)
|
|
25
|
+
boxes[:, 2] = torch.round(((boxes[:, 2] - pad_width) / width) * 100, decimals=2)
|
|
26
|
+
boxes[:, 3] = torch.round(((boxes[:, 3] - pad_height) / height) * 100, decimals=2)
|
|
27
|
+
# save annotations
|
|
28
|
+
results = []
|
|
29
|
+
for i in range(int(boxes.size(0))):
|
|
30
|
+
label_name = labels[int(prediction[0].boxes.cls[i].item())][1]
|
|
31
|
+
box_width = boxes[i, 2] - boxes[i, 0]
|
|
32
|
+
box_height = boxes[i, 3] - boxes[i, 1]
|
|
33
|
+
results.append({"type": "rectanglelabels",
|
|
34
|
+
"value": {"rotation": 0, "x": boxes[i, 0].item(), "y": boxes[i, 1].item(),
|
|
35
|
+
"width": box_width.item(), "height": box_height.item(),
|
|
36
|
+
"rectanglelabels": [label_name], },
|
|
37
|
+
"from_name": "label", "to_name": "image"})
|
|
38
|
+
return results
|
TSAnnotate/Export.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
from PIL import Image
|
|
4
|
+
from TSAnnotate.Load import load_labels
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def export(input_path, data_path, output_path="output", val_split=0.1, test_split=0.1, background_ratio=0.1, dataset_name="new_dataset", labels_path=None):
|
|
8
|
+
output_path = os.path.join(output_path, dataset_name)
|
|
9
|
+
annotations = json.load(open(input_path, "r"))
|
|
10
|
+
# map labels names to class ids
|
|
11
|
+
short_labels = {}
|
|
12
|
+
i = 0
|
|
13
|
+
for _, short_label, _ in load_labels(labels_path):
|
|
14
|
+
short_labels[short_label] = i
|
|
15
|
+
i += 1
|
|
16
|
+
# ensure output dirs exist
|
|
17
|
+
if not os.path.isdir(os.path.join(output_path, "images", "train")):
|
|
18
|
+
os.makedirs(os.path.join(output_path, "images", "train"))
|
|
19
|
+
if val_split > 0 and not os.path.isdir(os.path.join(output_path, "images", "val")):
|
|
20
|
+
os.makedirs(os.path.join(output_path, "images", "val"))
|
|
21
|
+
if test_split > 0 and not os.path.isdir(os.path.join(output_path, "images", "test")):
|
|
22
|
+
os.makedirs(os.path.join(output_path, "images", "test"))
|
|
23
|
+
if not os.path.isdir(os.path.join(output_path, "labels", "train")):
|
|
24
|
+
os.makedirs(os.path.join(output_path, "labels", "train"))
|
|
25
|
+
if val_split > 0 and not os.path.isdir(os.path.join(output_path, "labels", "val")):
|
|
26
|
+
os.makedirs(os.path.join(output_path, "labels", "val"))
|
|
27
|
+
if test_split > 0 and not os.path.isdir(os.path.join(output_path, "labels", "test")):
|
|
28
|
+
os.makedirs(os.path.join(output_path, "labels", "test"))
|
|
29
|
+
if not os.path.isdir(os.path.join(output_path, "excluded")):
|
|
30
|
+
os.makedirs(os.path.join(output_path, "excluded"))
|
|
31
|
+
# keep track of images in each split
|
|
32
|
+
train_images = 0
|
|
33
|
+
train_background = 0
|
|
34
|
+
val_images = 0
|
|
35
|
+
val_background = 0
|
|
36
|
+
test_images = 0
|
|
37
|
+
test_background = 0
|
|
38
|
+
excluded = 0
|
|
39
|
+
# iterate over all images
|
|
40
|
+
i = 1
|
|
41
|
+
for task in annotations:
|
|
42
|
+
print(f"\rProcessing image {i}/{len(annotations)}", end="", flush=True)
|
|
43
|
+
i += 1
|
|
44
|
+
image_name = task["data"]["image"].split("/")[-1]
|
|
45
|
+
image = Image.open(os.path.join(data_path, "images", image_name))
|
|
46
|
+
signs = []
|
|
47
|
+
# iterate over annotated signs
|
|
48
|
+
for result in task["annotations"][0]["result"]:
|
|
49
|
+
image_width = image.width
|
|
50
|
+
image_height = image.height
|
|
51
|
+
# get abs pixel values for bounding box
|
|
52
|
+
left = int((result["value"]["x"] / 100) * image_width)
|
|
53
|
+
top = int((result["value"]["y"] / 100) * image_height)
|
|
54
|
+
right = left + ((result["value"]["width"] / 100) * image_width)
|
|
55
|
+
bottom = top + ((result["value"]["height"] / 100) * image_height)
|
|
56
|
+
# convert into YOLO coordinates
|
|
57
|
+
center_x = int((left + right) / 2) / image_width
|
|
58
|
+
center_y = int((top + bottom) / 2) / image_height
|
|
59
|
+
width = (right - left) / image_width
|
|
60
|
+
height = (bottom - top) / image_height
|
|
61
|
+
# map short label name to class number
|
|
62
|
+
label = short_labels[result["value"]["rectanglelabels"][0]]
|
|
63
|
+
signs.append(str(label) + " " + str(center_x) + " " + str(center_y) + " " + str(width) + " " + str(height))
|
|
64
|
+
# determine which split to assign image to
|
|
65
|
+
if val_images + 1 <= (train_images + val_images + test_images + 1) * val_split:
|
|
66
|
+
split = "val"
|
|
67
|
+
elif test_images + 1 <= (train_images + val_images + test_images + 1) * test_split:
|
|
68
|
+
split = "test"
|
|
69
|
+
else:
|
|
70
|
+
split = "train"
|
|
71
|
+
# check if image is background and whether to include it
|
|
72
|
+
image_output_path = os.path.join(output_path, "images", split, image_name)
|
|
73
|
+
annotation_output_path = os.path.join(output_path, "labels", split, image_name.split(".")[0] + ".txt")
|
|
74
|
+
if len(signs) == 0:
|
|
75
|
+
# include background in train split if ratio not exceeded
|
|
76
|
+
if split == "train" and train_background + 1 <= train_images * background_ratio:
|
|
77
|
+
image.save(image_output_path)
|
|
78
|
+
with open(annotation_output_path, "w") as f:
|
|
79
|
+
for sign in signs:
|
|
80
|
+
f.write(sign + "\n")
|
|
81
|
+
train_images += 1
|
|
82
|
+
train_background += 1
|
|
83
|
+
# include background in val split if ratio not exceeded
|
|
84
|
+
elif split == "val" and val_background + 1 <= val_images * background_ratio:
|
|
85
|
+
image.save(image_output_path)
|
|
86
|
+
with open(annotation_output_path, "w") as f:
|
|
87
|
+
for sign in signs:
|
|
88
|
+
f.write(sign + "\n")
|
|
89
|
+
val_images += 1
|
|
90
|
+
val_background += 1
|
|
91
|
+
# include background in test split if ratio not exceeded
|
|
92
|
+
elif split == "test" and test_background + 1 <= test_images * background_ratio:
|
|
93
|
+
image.save(image_output_path)
|
|
94
|
+
with open(annotation_output_path, "w") as f:
|
|
95
|
+
for sign in signs:
|
|
96
|
+
f.write(sign + "\n")
|
|
97
|
+
test_images += 1
|
|
98
|
+
test_background += 1
|
|
99
|
+
# otherwise exclude background
|
|
100
|
+
else:
|
|
101
|
+
image.save(os.path.join(output_path, "excluded", image_name))
|
|
102
|
+
excluded += 1
|
|
103
|
+
# always include images with signs
|
|
104
|
+
else:
|
|
105
|
+
image.save(image_output_path)
|
|
106
|
+
with open(annotation_output_path, "w") as f:
|
|
107
|
+
for sign in signs:
|
|
108
|
+
f.write(sign + "\n")
|
|
109
|
+
if split == "train":
|
|
110
|
+
train_images += 1
|
|
111
|
+
elif split == "val":
|
|
112
|
+
val_images += 1
|
|
113
|
+
elif split == "test":
|
|
114
|
+
test_images += 1
|
|
115
|
+
print()
|
|
116
|
+
print("Exported " + str(train_images + val_images + test_images) + " images, excluded " + str(excluded))
|
|
117
|
+
print("Train split has " + str(train_images) + " images (" + str(train_background) + " background)")
|
|
118
|
+
print("Val split has " + str(val_images) + " images (" + str(val_background) + " background)")
|
|
119
|
+
print("Test split has " + str(test_images) + " images (" + str(test_background) + " background)")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def export_labeling_interface(output_path, labels_path=None):
|
|
123
|
+
labels = load_labels(labels_path)
|
|
124
|
+
with open(os.path.join(output_path, "labeling_interface.html"), "w") as f:
|
|
125
|
+
f.write("<View>\n")
|
|
126
|
+
f.write("<Image name=\"image\" value=\"$image\"/>\n")
|
|
127
|
+
f.write("<RectangleLabels name=\"label\" toName=\"image\">\n")
|
|
128
|
+
for _, short_label, color in labels:
|
|
129
|
+
f.write("<Label value=\"" + short_label + "\" background=\"" + color + "\"/>\n")
|
|
130
|
+
f.write("</RectangleLabels>\n")
|
|
131
|
+
f.write("</View>\n")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def export_yolo_meta(output_path="output", dataset_name="new_dataset", labels_path=None, val_split=0.1, test_split=0.1):
|
|
135
|
+
with open(os.path.join(output_path, dataset_name, dataset_name + ".yaml"), "w", encoding="utf-8") as f:
|
|
136
|
+
f.write("path: " + dataset_name + "\n")
|
|
137
|
+
f.write("train: images/train" + "\n")
|
|
138
|
+
if val_split > 0:
|
|
139
|
+
f.write("val: images/val" + "\n")
|
|
140
|
+
if test_split > 0:
|
|
141
|
+
f.write("test: images/test" + "\n\n")
|
|
142
|
+
f.write("names:" + "\n")
|
|
143
|
+
i = 0
|
|
144
|
+
for label, _, __ in load_labels(labels_path):
|
|
145
|
+
f.write(" " + str(i) + ": " + label + "\n")
|
|
146
|
+
i += 1
|
TSAnnotate/Filter.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import cv2
|
|
2
|
+
import numpy as np
|
|
3
|
+
from skimage.metrics import structural_similarity
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def filter_similar(image1, image2, threshold=0.8):
|
|
7
|
+
assert 0 < threshold < 1.0, "Similarity threshold should be between 0 and 1"
|
|
8
|
+
image1 = np.array(image1)
|
|
9
|
+
image2 = np.array(image2)
|
|
10
|
+
# resize images
|
|
11
|
+
image2 = cv2.resize(image2, (image1.shape[1], image1.shape[0]))
|
|
12
|
+
# convert to grayscale
|
|
13
|
+
gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
|
|
14
|
+
gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
|
|
15
|
+
# calculate SSIM
|
|
16
|
+
score, _ = structural_similarity(gray1, gray2, full=True, data_range=255)
|
|
17
|
+
if score > threshold:
|
|
18
|
+
return True
|
|
19
|
+
else:
|
|
20
|
+
return False
|
TSAnnotate/Load.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import numpy as np
|
|
3
|
+
from PIL import Image
|
|
4
|
+
from ultralytics import YOLO
|
|
5
|
+
from importlib.resources import read_text
|
|
6
|
+
from huggingface_hub import hf_hub_download
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
SUPPORTED_VIDEOS = ["mov", "mp4"]
|
|
10
|
+
SUPPORTED_IMAGES = ["jpg", "jpeg", "png"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_paths(input_path):
|
|
14
|
+
if os.path.isdir(input_path):
|
|
15
|
+
return sorted(load_paths_from_dir(input_path))
|
|
16
|
+
else:
|
|
17
|
+
if is_video(input_path) or is_image(input_path):
|
|
18
|
+
return [input_path]
|
|
19
|
+
else:
|
|
20
|
+
raise RuntimeError("Input file type not supported: " + input_path.split(".")[-1])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def load_paths_from_dir(dir_path):
|
|
24
|
+
files = []
|
|
25
|
+
for path in os.listdir(dir_path):
|
|
26
|
+
total_path = os.path.join(dir_path, path)
|
|
27
|
+
if os.path.isdir(total_path):
|
|
28
|
+
files.extend(load_paths_from_dir(total_path))
|
|
29
|
+
else:
|
|
30
|
+
if is_video(total_path) or is_image(total_path):
|
|
31
|
+
files.append(total_path)
|
|
32
|
+
return files
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def load_image(image_path):
|
|
36
|
+
return Image.open(image_path)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def is_video(path):
|
|
40
|
+
return path.split(".")[-1] in SUPPORTED_VIDEOS
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_image(path):
|
|
44
|
+
return path.split(".")[-1] in SUPPORTED_IMAGES
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def load_labels(path=None):
|
|
48
|
+
labels = []
|
|
49
|
+
if path is None:
|
|
50
|
+
for line in read_text("TSAnnotate.data", "labels.csv", encoding="utf-8").split("\n"):
|
|
51
|
+
if line.strip() != "":
|
|
52
|
+
labels.append(line.strip().split(","))
|
|
53
|
+
else:
|
|
54
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
55
|
+
for line in f:
|
|
56
|
+
if line.strip() != "":
|
|
57
|
+
labels.append(line.strip().split(","))
|
|
58
|
+
if len(labels) == 0:
|
|
59
|
+
raise RuntimeError("No labels loaded from custom file: " + path)
|
|
60
|
+
return labels
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def load_model(path=None):
|
|
64
|
+
if path is None:
|
|
65
|
+
try:
|
|
66
|
+
checkpoint = hf_hub_download(repo_id="dsilbermann/traffic_sign_detection_europe", filename="model.pt")
|
|
67
|
+
return YOLO(checkpoint)
|
|
68
|
+
except:
|
|
69
|
+
raise RuntimeError("Failed to load default model from HuggingFace")
|
|
70
|
+
elif os.path.isfile(path):
|
|
71
|
+
try:
|
|
72
|
+
return YOLO(path)
|
|
73
|
+
except:
|
|
74
|
+
raise FileNotFoundError("Model could not be loaded from " + path)
|
|
75
|
+
else:
|
|
76
|
+
path_split = path.split("/")
|
|
77
|
+
repo_id = path_split[0] + "/" + path_split[1]
|
|
78
|
+
filename = path_split[2]
|
|
79
|
+
try:
|
|
80
|
+
checkpoint = hf_hub_download(repo_id=repo_id, filename=filename)
|
|
81
|
+
return YOLO(checkpoint)
|
|
82
|
+
except:
|
|
83
|
+
raise RuntimeError("Failed to load custom model from HuggingFace at " + path +
|
|
84
|
+
"; path must include filename like this: user/repo/filename.pt")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def sort_paths(paths):
|
|
88
|
+
sort_by = []
|
|
89
|
+
for path in paths:
|
|
90
|
+
path = path.split(".")[0].split("/")[-1]
|
|
91
|
+
# split file name and look for numbers to sort by
|
|
92
|
+
for c1 in path.split("_"):
|
|
93
|
+
found_number = False
|
|
94
|
+
for c2 in c1.split("-"):
|
|
95
|
+
try:
|
|
96
|
+
c_int = int(c2)
|
|
97
|
+
except:
|
|
98
|
+
continue
|
|
99
|
+
sort_by.append(c_int)
|
|
100
|
+
found_number = True
|
|
101
|
+
break
|
|
102
|
+
if found_number:
|
|
103
|
+
break
|
|
104
|
+
sort_by = np.array(sort_by)
|
|
105
|
+
sorted_indices = np.argsort(sort_by)
|
|
106
|
+
result = []
|
|
107
|
+
for index in sorted_indices:
|
|
108
|
+
result.append(paths[index])
|
|
109
|
+
return result
|
TSAnnotate/Main.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
import argparse
|
|
4
|
+
from TSAnnotate.Annotate import annotate
|
|
5
|
+
from TSAnnotate.Sample import sample_video
|
|
6
|
+
from TSAnnotate.Filter import filter_similar
|
|
7
|
+
from TSAnnotate.Export import export, export_yolo_meta, export_labeling_interface
|
|
8
|
+
from TSAnnotate.Load import load_paths, load_image, is_video, is_image, sort_paths
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
parser = argparse.ArgumentParser(prog="TSAnnotate",
|
|
12
|
+
description="Quickly annotate images for traffic sign detection and recognition by "
|
|
13
|
+
"using pre-trained models.")
|
|
14
|
+
parser.add_argument('--version', action='version', version='%(prog)s 0.0.1')
|
|
15
|
+
parser.add_argument("task", type=str, choices=["label", "export"], help="Task to run")
|
|
16
|
+
parser.add_argument("input_path", help="Path to input, can be directory or file")
|
|
17
|
+
parser.add_argument("-o", "--output_path", default="output", help="Output directory or file")
|
|
18
|
+
parser.add_argument("-sr", "--sample_rate", default=1, help="Rate at which to extract images from videos")
|
|
19
|
+
parser.add_argument("-d", "--data_path", default=None,
|
|
20
|
+
help="Where to look for images and annotations when export task is run")
|
|
21
|
+
parser.add_argument("-vs", "--val_split", default=0.1, type=float,
|
|
22
|
+
help="Fraction of images to use for validation")
|
|
23
|
+
parser.add_argument("-ts", "--test_split", default=0.1, type=float,
|
|
24
|
+
help="Fraction of images to use for testing")
|
|
25
|
+
parser.add_argument("-br", "--background_ratio", default=0.1, type=float,
|
|
26
|
+
help="Maximum ratio of background images in each split")
|
|
27
|
+
parser.add_argument("-n", "--name", default="new_dataset", dest="dataset_name",
|
|
28
|
+
help="Name of the exported dataset")
|
|
29
|
+
parser.add_argument("-l", "--labels", default=None, dest="labels_path", help="Path to custom labels file")
|
|
30
|
+
parser.add_argument("-m", "--model", default=None, dest="model_path", help="Path to custom model")
|
|
31
|
+
parser.add_argument("-fs", "--filter_similar", default=None, const=0.8, type=float, nargs="?",
|
|
32
|
+
help="Filter out successive images that exceed the given similarity threshold")
|
|
33
|
+
parser.add_argument("-si", "--sort_inputs", action="store_true",
|
|
34
|
+
help="Sort inputs by numbers extracted from file names; numbers must be separated by '_' or '-'")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def main():
|
|
38
|
+
args = parser.parse_args()
|
|
39
|
+
# ensure output dirs exist
|
|
40
|
+
if not os.path.exists(args.output_path):
|
|
41
|
+
os.makedirs(args.output_path)
|
|
42
|
+
if args.task == "label":
|
|
43
|
+
if not os.path.exists(os.path.join(args.output_path, "images")):
|
|
44
|
+
os.makedirs(os.path.join(args.output_path, "images"))
|
|
45
|
+
if not os.path.exists(os.path.join(args.output_path, "annotations")):
|
|
46
|
+
os.makedirs(os.path.join(args.output_path, "annotations"))
|
|
47
|
+
input_paths = load_paths(args.input_path)
|
|
48
|
+
# sort paths in flag is set
|
|
49
|
+
if args.sort_inputs:
|
|
50
|
+
input_paths = sort_paths(input_paths)
|
|
51
|
+
print("Collected " + str(len(input_paths)) + " files")
|
|
52
|
+
num_images = 0
|
|
53
|
+
i = 1
|
|
54
|
+
prev_image = None
|
|
55
|
+
filtered_images = 0
|
|
56
|
+
for path in input_paths:
|
|
57
|
+
print(f"\rProcessing file {i}/{len(input_paths)}", end="", flush=True)
|
|
58
|
+
if is_image(path):
|
|
59
|
+
image = load_image(path)
|
|
60
|
+
# filter out similar images if argument is set
|
|
61
|
+
if args.filter_similar is not None:
|
|
62
|
+
if i == 1 and not args.sort_inputs:
|
|
63
|
+
print("Warning: input files should be sorted for reliable filtering")
|
|
64
|
+
if prev_image is not None:
|
|
65
|
+
if filter_similar(prev_image, image, threshold=args.filter_similar):
|
|
66
|
+
filtered_images += 1
|
|
67
|
+
continue
|
|
68
|
+
prev_image = image
|
|
69
|
+
annotations = annotate(image, args.labels_path, args.model_path)
|
|
70
|
+
# save image
|
|
71
|
+
image.save(os.path.join(args.output_path, "images", str(num_images) + ".jpg"))
|
|
72
|
+
# save annotations
|
|
73
|
+
task = {"id": str(num_images), "data": {"image": "/data/local-files/?d=images/" + str(num_images) + ".jpg"},
|
|
74
|
+
"annotations": [{"result": annotations}]}
|
|
75
|
+
json.dump(task, open(os.path.join(args.output_path, "annotations", str(num_images) + ".json"), "w"))
|
|
76
|
+
num_images += 1
|
|
77
|
+
elif is_video(path):
|
|
78
|
+
for image in sample_video(path, sample_rate=float(args.sample_rate)):
|
|
79
|
+
# filter out similar images if argument is set
|
|
80
|
+
if args.filter_similar is not None and prev_image is not None:
|
|
81
|
+
if filter_similar(prev_image, image, threshold=args.filter_similar):
|
|
82
|
+
filtered_images += 1
|
|
83
|
+
continue
|
|
84
|
+
prev_image = image
|
|
85
|
+
annotations = annotate(image, args.labels_path, args.model_path)
|
|
86
|
+
# save image
|
|
87
|
+
image.save(os.path.join(args.output_path, "images", str(num_images) + ".jpg"))
|
|
88
|
+
# save annotations
|
|
89
|
+
task = {"id": str(num_images),
|
|
90
|
+
"data": {"image": "/data/local-files/?d=images/" + str(num_images) + ".jpg"},
|
|
91
|
+
"annotations": [{"result": annotations}]}
|
|
92
|
+
json.dump(task, open(os.path.join(args.output_path, "annotations", str(num_images) + ".json"), "w"))
|
|
93
|
+
num_images += 1
|
|
94
|
+
i += 1
|
|
95
|
+
print()
|
|
96
|
+
if args.filter_similar is not None:
|
|
97
|
+
print("Filtered out " + str(filtered_images) + " images due to similarity")
|
|
98
|
+
export_labeling_interface(args.output_path, args.labels_path)
|
|
99
|
+
elif args.task == "export":
|
|
100
|
+
# check where images and annotations are stored
|
|
101
|
+
data_path = None
|
|
102
|
+
# if data_path is set, check there first
|
|
103
|
+
if args.data_path is not None:
|
|
104
|
+
if not os.path.exists(os.path.join(args.data_path, "images")):
|
|
105
|
+
raise RuntimeError("No images found in data path: " + args.data_path)
|
|
106
|
+
if not os.path.exists(os.path.join(args.data_path, "annotations")):
|
|
107
|
+
raise RuntimeError("No annotations found in data path: " + args.data_path)
|
|
108
|
+
data_path = args.data_path
|
|
109
|
+
# otherwise, check in output path
|
|
110
|
+
elif os.path.exists(os.path.join(args.output_path, "images")) and os.path.exists(os.path.join(args.output_path, "annotations")):
|
|
111
|
+
data_path = args.output_path
|
|
112
|
+
# if unsuccessful, check default output path
|
|
113
|
+
elif args.output_path != "output" and os.path.exists(os.path.join("output", "images")) and os.path.exists(os.path.join("output", "annotations")):
|
|
114
|
+
data_path = "output"
|
|
115
|
+
# if still not found, check Label Studio local files root; only works if it was launched from same shell
|
|
116
|
+
elif os.environ.get("LABEL_STUDIO_LOCAL_FILES_DOCUMENT_ROOT") is not None:
|
|
117
|
+
label_studio_root = str(os.environ.get("LABEL_STUDIO_LOCAL_FILES_DOCUMENT_ROOT"))
|
|
118
|
+
if os.path.exists(os.path.join(label_studio_root, "images")) and os.path.exists(os.path.join(label_studio_root, "annotations")):
|
|
119
|
+
data_path = label_studio_root
|
|
120
|
+
# check if data path was found
|
|
121
|
+
if data_path is None:
|
|
122
|
+
raise RuntimeError("Image and annotation data could not be found. Use the 'data_path' argument to define "
|
|
123
|
+
"the output directory generated by the 'label' task containing the 'images' and "
|
|
124
|
+
"'annotations' directories. If 'data_path' was set, check if it points to the correct "
|
|
125
|
+
"directory.")
|
|
126
|
+
export(args.input_path, data_path, args.output_path, args.val_split, args.test_split, args.background_ratio, args.dataset_name, args.labels_path)
|
|
127
|
+
export_yolo_meta(args.output_path, args.dataset_name, args.labels_path, args.val_split, args.test_split)
|
|
128
|
+
return 0
|
TSAnnotate/Sample.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from torchcodec.decoders import VideoDecoder
|
|
2
|
+
from torchvision.transforms.v2.functional import to_pil_image
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def sample_video(video_path, sample_rate=1):
|
|
6
|
+
video = VideoDecoder(video_path)
|
|
7
|
+
num_frames = int(video.metadata.duration_seconds * sample_rate) + 1
|
|
8
|
+
# check sample rate
|
|
9
|
+
fps = video.metadata.average_fps
|
|
10
|
+
assert sample_rate <= fps, ("Sample rate (" + str(sample_rate) + ") should not be larger than video FPS ("
|
|
11
|
+
+ str(fps) + ")")
|
|
12
|
+
assert sample_rate > 0, "Sample rate should be larger than 0"
|
|
13
|
+
i = 1
|
|
14
|
+
print()
|
|
15
|
+
# extract frames
|
|
16
|
+
for frame in video[::int(round(fps / sample_rate, 0))]:
|
|
17
|
+
print(f"\rExtracting frame {i}/{num_frames}", end="", flush=True)
|
|
18
|
+
i += 1
|
|
19
|
+
yield to_pil_image(frame)
|
TSAnnotate/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
Right bend,Right bend,#BA280F
|
|
2
|
+
Left bend,Left bend,#BA280F
|
|
3
|
+
Double bend (left),Double bend (left),#BA280F
|
|
4
|
+
Double bend (right),Double bend (right),#BA280F
|
|
5
|
+
Dangerous descent,Descent,#BA280F
|
|
6
|
+
Steep ascent,Ascent,#BA280F
|
|
7
|
+
Carriageway narrows (both),Carriageway narrows (both),#BA280F
|
|
8
|
+
Carriageway narrows (right),Carriageway narrows (right),#BA280F
|
|
9
|
+
Carriageway narrows (left),Carriageway narrows (left),#BA280F
|
|
10
|
+
Road leads on to quay or river bank,Quay or river bank,#BA280F
|
|
11
|
+
Uneven road (1 bump),Uneven (1 bump),#BA280F
|
|
12
|
+
Uneven road (2 bump),Uneven (2 bump),#BA280F
|
|
13
|
+
Slippery road,Slippery,#BA280F
|
|
14
|
+
Loose gravel,Loose gravel,#BA280F
|
|
15
|
+
Falling rocks,Falling rocks,#BA280F
|
|
16
|
+
Pedestrian crossing,Pedestrian crossing,#BA280F
|
|
17
|
+
Children (School),Children (School),#BA280F
|
|
18
|
+
Cyclists entering or crossing,Cyclists,#BA280F
|
|
19
|
+
Domestic animals crossing,Domestic animals,#BA280F
|
|
20
|
+
Wild animals crossing,Wild animals,#BA280F
|
|
21
|
+
Road works,Road works,#BA280F
|
|
22
|
+
Light signals,Light signals,#BA280F
|
|
23
|
+
Intersection,Intersection,#BA280F
|
|
24
|
+
Intersection with road (priority),Intersection with road (priority),#BA280F
|
|
25
|
+
Roundabout,Roundabout,#BA280F
|
|
26
|
+
Two-way traffic,Two-way traffic,#BA280F
|
|
27
|
+
Level-crossings with gates,Level-crossings with gates,#BA280F
|
|
28
|
+
Other level-crossings,Other level-crossings,#BA280F
|
|
29
|
+
Immediate level-crossing,Immediate level-crossing,#BA280F
|
|
30
|
+
Level-crossings additional signs,Level-crossings additional signs,#BA280F
|
|
31
|
+
Airfield,Airfield,#BA280F
|
|
32
|
+
Other dangers,Other dangers,#BA280F
|
|
33
|
+
Snow,Snow,#BA280F
|
|
34
|
+
Riders on horseback,Riders on horseback,#BA280F
|
|
35
|
+
Give way,Give way,#0FBA1D
|
|
36
|
+
Stop,Stop,#0FBA1D
|
|
37
|
+
Priority road,Priority road,#0FBA1D
|
|
38
|
+
End of priority,End of priority,#0FBA1D
|
|
39
|
+
Priority for oncoming traffic,Priority for oncoming traffic,#0FBA1D
|
|
40
|
+
Priority over oncoming traffic,Priority over oncoming traffic,#0FBA1D
|
|
41
|
+
No entry,No entry,#79E07D
|
|
42
|
+
Closed to all vehicles in both directions,Closed to all vehicles in both directions,#79E07D
|
|
43
|
+
No entry for cycles,No entry (cycles),#79E07D
|
|
44
|
+
No entry for vehicle drawing a trailer,No entry (trailer),#79E07D
|
|
45
|
+
No entry for power driven vehicles,No entry (power driven vehicles),#79E07D
|
|
46
|
+
No entry for vehicles having an overall width exceeding … meters,No entry (width),#79E07D
|
|
47
|
+
No entry for vehicles having an overall height exceeding … meters,No entry (height),#79E07D
|
|
48
|
+
No entry for vehicles exceeding … tonnes laden mass,No entry (weight),#79E07D
|
|
49
|
+
No entry for vehicles having a mass exceeding … tonnes on one axle,No entry (weight per axle),#79E07D
|
|
50
|
+
No entry for trucks,No entry (trucks) ,#79E07D
|
|
51
|
+
No left turn,No left turn,#79E07D
|
|
52
|
+
No right turn,No right turn ,#79E07D
|
|
53
|
+
No U-turn,No U-turn,#79E07D
|
|
54
|
+
Overtaking prohibited,Overtaking prohibited,#79E07D
|
|
55
|
+
Overtaking by goods vehicles prohibited,Overtaking by goods vehicles prohibited,#79E07D
|
|
56
|
+
Maximum speed limit 10,10,#79E07D
|
|
57
|
+
Maximum speed limit 20,20,#79E07D
|
|
58
|
+
Maximum speed limit 25,25,#79E07D
|
|
59
|
+
Maximum speed limit 30,30,#79E07D
|
|
60
|
+
Maximum speed limit 40,40,#79E07D
|
|
61
|
+
Maximum speed limit 50,50,#79E07D
|
|
62
|
+
Maximum speed limit 60,60,#79E07D
|
|
63
|
+
Maximum speed limit 70,70,#79E07D
|
|
64
|
+
Maximum speed limit 80,80,#79E07D
|
|
65
|
+
Maximum speed limit 90,90,#79E07D
|
|
66
|
+
Maximum speed limit 100,100,#79E07D
|
|
67
|
+
Maximum speed limit 110,110,#79E07D
|
|
68
|
+
Maximum speed limit 120,120,#79E07D
|
|
69
|
+
Passing without stopping prohibited (customs),Customs,#79E07D
|
|
70
|
+
End of all local prohibitions imposed on moving vehicles,End of all local prohibitions,#79E07D
|
|
71
|
+
End of maximum speed limit,End of maximum speed limit,#79E07D
|
|
72
|
+
End of prohibition of overtaking,End of prohibition of overtaking,#79E07D
|
|
73
|
+
End of prohibition of overtaking for goods vehicles,End of prohibition of overtaking for goods vehicles,#79E07D
|
|
74
|
+
Parking prohibited,Parking prohibited ,#79E07D
|
|
75
|
+
Parking prohibited (first half month),Parking prohibited (first half month),#79E07D
|
|
76
|
+
Parking prohibited (last half month),Parking prohibited (last half month),#79E07D
|
|
77
|
+
Standing and parking prohibited,Standing and parking prohibited ,#79E07D
|
|
78
|
+
End of parking prohibited,End of parking prohibited ,#79E07D
|
|
79
|
+
No photos,No photos,#79E07D
|
|
80
|
+
Direction – Straight,Straight,#42FF4A
|
|
81
|
+
Direction – Right,Right,#42FF4A
|
|
82
|
+
Direction – Left,Left,#42FF4A
|
|
83
|
+
Direction – Straight or Right,Straight or Right,#42FF4A
|
|
84
|
+
Direction – Straight or Left,Straight or Left,#42FF4A
|
|
85
|
+
Direction – Turn right,Turn right,#42FF4A
|
|
86
|
+
Direction – Turn left,Turn left,#42FF4A
|
|
87
|
+
Pass Right,Pass Right,#42FF4A
|
|
88
|
+
Pass Left,Pass Left,#42FF4A
|
|
89
|
+
Pass Either side,Pass Either side,#42FF4A
|
|
90
|
+
Compulsory roundabout,Roundabout (m),#42FF4A
|
|
91
|
+
Compulsory cycle track,Cycle track,#42FF4A
|
|
92
|
+
Compulsory footpath,Footpath,#42FF4A
|
|
93
|
+
Compulsory cycle track - footpath (split),Cycle track - footpath (split),#42FF4A
|
|
94
|
+
Compulsory cycle track - footpath (shared),Cycle track - footpath (shared),#42FF4A
|
|
95
|
+
Compulsory bus,Compulsory - Bus,#42FF4A
|
|
96
|
+
End of compulsory bus,End of compulsory bus,#42FF4A
|
|
97
|
+
End of compulsory cycle track,End Cycle track,#42FF4A
|
|
98
|
+
End of pedestrian track,End of pedestrian track,#42FF4A
|
|
99
|
+
Lanes reserved for certain vehicle type,Lanes reserved for certain vehicle type,#3CF09C
|
|
100
|
+
One-way (Straight),One-way (Straight),#3CF09C
|
|
101
|
+
One-way (Right),One-way (Right),#3CF09C
|
|
102
|
+
One-way (Left),One-way (Left),#3CF09C
|
|
103
|
+
Motorway,Motorway,#3CF09C
|
|
104
|
+
Road for motor vehicles,Road for motor vehicles,#3CF09C
|
|
105
|
+
Beginning of area (town),Beginning of area (town),#3CF09C
|
|
106
|
+
End of area (town),End of area (town),#3CF09C
|
|
107
|
+
Maximum speed zone,Maximum speed zone,#3CF09C
|
|
108
|
+
End of maximum speed zone,End of maximum speed zone,#3CF09C
|
|
109
|
+
Pedestrian crossing,Pedestrian crossing (s),#3CF09C
|
|
110
|
+
Parking,Parking,#3CF09C
|
|
111
|
+
Parking for handicap,Parking for handicap,#3CF09C
|
|
112
|
+
Parking for cars,Parking for cars,#3CF09C
|
|
113
|
+
Parking for goods vehicles,Parking for goods vehicles,#3CF09C
|
|
114
|
+
Parking for bus,Parking for bus,#3CF09C
|
|
115
|
+
Parking on pavement or verge,Parking on pavement or verge,#3CF09C
|
|
116
|
+
Parking on the right,Parking on the right,#3CF09C
|
|
117
|
+
Parking on the left,Parking on the left,#3CF09C
|
|
118
|
+
Parking garage,Parking garage,#3CF09C
|
|
119
|
+
Bus stop,Bus stop,#3CF09C
|
|
120
|
+
Cyclists-Pedestrians,Cyclists-Pedestrians (s),#3CF09C
|
|
121
|
+
Cycle track,Cycle track (s),#3CF09C
|
|
122
|
+
Cyclists entering or crossing,Cyclists entering or crossing (s),#3CF09C
|
|
123
|
+
Residential area,Residential area,#3CF09C
|
|
124
|
+
End of residential area,End of residential area,#3CF09C
|
|
125
|
+
Uneven road (1 bump),Uneven road (1 bump),#3CF09C
|
|
126
|
+
Pass right,Pass right (s),#3CF09C
|
|
127
|
+
End of road works,End of road works,#3C45F0
|
|
128
|
+
Filling station,Filling station,#3C45F0
|
|
129
|
+
Hotel or motel,Hotel or motel,#3C45F0
|
|
130
|
+
Restaurant,Restaurant,#3C45F0
|
|
131
|
+
Refreshments or cafeteria,Refreshments or cafeteria,#3C45F0
|
|
132
|
+
Children on the road,Children on the road,#3C45F0
|
|
133
|
+
School patrol,School patrol,#3C45F0
|
|
134
|
+
Water protection area,Water protection area,#3C45F0
|
|
135
|
+
River,River,#3C45F0
|
|
136
|
+
Road construction,Road construction,#3C45F0
|
|
137
|
+
Police station,Police station,#3C45F0
|
|
138
|
+
Radio station,Radio station,#3C45F0
|
|
139
|
+
Advance direction signs,Advance direction signs,#869BDB
|
|
140
|
+
Direction to place,Direction to place,#869BDB
|
|
141
|
+
Number and direction of traffic lanes,Number and direction of traffic lanes,#869BDB
|
|
142
|
+
Closure of a traffic lane,Closure of a traffic lane,#869BDB
|
|
143
|
+
No through road (dead end),No through road (dead end),#869BDB
|
|
144
|
+
General speed limits,General speed limits,#869BDB
|
|
145
|
+
Exit from motorway,Exit from motorway,#869BDB
|
|
146
|
+
Carriage of vehicles (lane directions),Carriage of vehicles (lane directions),#869BDB
|
|
147
|
+
Distance to place,Distance to place,#56E1F0
|
|
148
|
+
Length of dangerous section,Length of dangerous section,#56E1F0
|
|
149
|
+
Intersection priority,Intersection priority,#56E1F0
|
|
150
|
+
Ice/Snow,Ice/Snow,#56E1F0
|
|
151
|
+
Directional panel (arrows),Directional panel (arrows),#56E1F0
|
|
152
|
+
Tram,Tram,#56E1F0
|
|
153
|
+
Car,Car,#56E1F0
|
|
154
|
+
Bus,Bus,#56E1F0
|
|
155
|
+
Truck,Truck,#56E1F0
|
|
156
|
+
Handicap,Handicap,#56E1F0
|
|
157
|
+
Bicycle,Bicycle,#56E1F0
|
|
158
|
+
Timing,Timing,#56E1F0
|
|
159
|
+
Supplemental panel,Supplemental panel,#56E1F0
|
|
160
|
+
Limited access on side,Limited access on side,#D9873B
|
|
161
|
+
Curve right,Curve right,#D9873B
|
|
162
|
+
Curve left,Curve left,#D9873B
|
|
163
|
+
Barrier,Barrier,#D9873B
|
|
164
|
+
Obstacle,Obstacle,#D9873B
|
|
165
|
+
Other warning,Other warning,#FCFCFC
|
|
166
|
+
Other priority,Other priority,#FCFCFC
|
|
167
|
+
Other prohibitory,Other prohibitory,#FCFCFC
|
|
168
|
+
Other mandatory,Other mandatory,#FCFCFC
|
|
169
|
+
Other special regulation,Other special regulation,#FCFCFC
|
|
170
|
+
Other (blue) information signs,Other (blue) information signs,#FCFCFC
|
|
171
|
+
Other signs,Other signs,#FCFCFC
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: TSAnnotate
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Quickly annotate images for traffic sign detection and recognition by using pre-trained models.
|
|
5
|
+
Author-email: David Silbermann <david.silbermann@rub.de>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/d-silbermann/TSAnnotate
|
|
8
|
+
Project-URL: Issues, https://github.com/d-silbermann/TSAnnotate/issues
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: torch>=2.14.1
|
|
15
|
+
Requires-Dist: torchvision>=0.29.1
|
|
16
|
+
Requires-Dist: torchcodec>=0.16.0
|
|
17
|
+
Requires-Dist: ultralytics>=8.4.190
|
|
18
|
+
Requires-Dist: pillow>=12.3.0
|
|
19
|
+
Requires-Dist: scikit-image>=0.25.2
|
|
20
|
+
Requires-Dist: opencv-python>=4.11.0.86
|
|
21
|
+
Requires-Dist: huggingface-hub>=2.4.0
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# TSAnnotate - Fast Traffic Sign Annotation
|
|
25
|
+
|
|
26
|
+
This tool supports the creation of traffic sign detection and recognition datasets by leveraging pre-trained
|
|
27
|
+
models to annotate traffic scenes from videos or images. It processes videos and images and exports the
|
|
28
|
+
pre-labeled scenes to [Label Studio](https://labelstud.io/) for manual verification and correction.
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
1. If not already available on your system, install FFmpeg
|
|
33
|
+
2. Python 3.10 or newer is required
|
|
34
|
+
3. Install from PyPI using `pip install TSAnnotate`
|
|
35
|
+
4. Install Label Studio using `pip install label-studio`
|
|
36
|
+
|
|
37
|
+
## Workflow
|
|
38
|
+
|
|
39
|
+
The workflow for creating traffic sign detection and recognition datasets using TSAnnotate and Label Studio
|
|
40
|
+
is the following:
|
|
41
|
+
1. Collect: obtain traffic scene data as videos or images
|
|
42
|
+
2. Label: pre-label traffic scenes with TSAnnotate; videos are sampled at the given rate and images are
|
|
43
|
+
processed as they are
|
|
44
|
+
3. Verify: manually check and correct the labels using Label Studio
|
|
45
|
+
4. Export: TSAnnotate creates train/test splits, filters out background images and converts annotations into
|
|
46
|
+
the YOLO format
|
|
47
|
+
|
|
48
|
+
## How to use
|
|
49
|
+
|
|
50
|
+
This section contains detailed information on each step.
|
|
51
|
+
|
|
52
|
+
### Data Collection
|
|
53
|
+
|
|
54
|
+
TSAnnotate can read either individual files or entire directories. In case of directories, all subdirectories will
|
|
55
|
+
be recursively searched for image and video files. The following file formats are supported:
|
|
56
|
+
- Videos: mov, mp4
|
|
57
|
+
- Images: jpg, jpeg, png
|
|
58
|
+
|
|
59
|
+
Unsupported files will be ignored, if the given input is a directory, or cause an exception, if the file is the
|
|
60
|
+
only input.
|
|
61
|
+
|
|
62
|
+
### Label
|
|
63
|
+
|
|
64
|
+
Run the following command to start pre-labeling:
|
|
65
|
+
|
|
66
|
+
`ts-annotate label /path/to/input`
|
|
67
|
+
|
|
68
|
+
Replace `/path/to/input` with the path to your input file or directory. The labeled images are exported to
|
|
69
|
+
an `output` directory in the current working directory. See the Arguments section on how to change this, and
|
|
70
|
+
other default behaviors. Annotations are stored in the Label Studio specific [format](https://labelstud.io/guide/task_format).
|
|
71
|
+
|
|
72
|
+
### Verify
|
|
73
|
+
|
|
74
|
+
Verification and correction is done manually in Label Studio. To enable import of local files to Label Studio,
|
|
75
|
+
run
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
export LABEL_STUDIO_LOCAL_FILES_SERVING_ENABLED=true
|
|
79
|
+
export LABEL_STUDIO_LOCAL_FILES_DOCUMENT_ROOT="/path/to/output"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
If you are using Windows the commands are different, please ask an LLM of your choice how to do this.
|
|
83
|
+
Replace `/path/to/output` with the output directory of the previous step. This must be done every time
|
|
84
|
+
Label Studio is started. Then run Label Studio:
|
|
85
|
+
|
|
86
|
+
`label-studio start`
|
|
87
|
+
|
|
88
|
+
Label Studio should automatically open in your browser, otherwise visit `http://localhost:8080` and follow these steps:
|
|
89
|
+
1. Create an account and sign in
|
|
90
|
+
2. Create a new project
|
|
91
|
+
3. Enter a name for the project
|
|
92
|
+
4. Go to the "Labeling setup" tab at the top of the window.
|
|
93
|
+
5. Select "object detection with bounding boxes"
|
|
94
|
+
6. On the left side, under "Labeling Interface", switch to the "Code" tab
|
|
95
|
+
7. Replace the entire content of the text box with the content of "labeling_interface.html" generated by
|
|
96
|
+
TSAnnotate in the output directory
|
|
97
|
+
8. Press "Save" in the top right. **Do not import any data yet.**
|
|
98
|
+
9. Press "Connect cloud storage"
|
|
99
|
+
10. Select "Local files" and press "Next"
|
|
100
|
+
11. Chose a "Storage Title" for this connection, e.g., "Images" as this is the image import
|
|
101
|
+
12. Point "Absolute local path" to the "images" directory inside the output generated by TSAnnotate,
|
|
102
|
+
e.g., `/path/to/output/images`
|
|
103
|
+
13. Optional: press "Test connection" to make sure the path was entered correctly
|
|
104
|
+
14. Press "Next"
|
|
105
|
+
15. Don't change anything on this page and press "Next"
|
|
106
|
+
16. Press "Save". **Do not press "Save & Sync".**
|
|
107
|
+
17. The same process is now repeated to import the annotations. Press "Add Source Storage"
|
|
108
|
+
18. Select "Local files" and press "Next"
|
|
109
|
+
19. Chose a "Storage Title", e.g., "Annotations"
|
|
110
|
+
20. Point "Absolute local path" to the "annotations" directory inside the output, e.g., `/path/to/output/annotations`
|
|
111
|
+
21. Optional: test the connection
|
|
112
|
+
22. Press "Next"
|
|
113
|
+
23. Don't change anything on this page and press "Next"
|
|
114
|
+
24. Press "Save & Sync", depending on the amount of images this may take a while
|
|
115
|
+
|
|
116
|
+
You can now click the name of you project on the top of the page to get to a list of the images. From here you can
|
|
117
|
+
select images. Some notes on using Label Studio:
|
|
118
|
+
- Remove duplicate/similar images directly from the list by marking them using the checkbox in the first column
|
|
119
|
+
and selecting "Delete Tasks" from the drop-down menu above
|
|
120
|
+
- Labels are based on the [ETSD](https://ieeexplore.ieee.org/abstract/document/8558481), some of them are "special"
|
|
121
|
+
versions of regular signs: "Cyclists-Pedestrians (s)", "Cycle track (s)", "Cyclists entering or crossing (s)",
|
|
122
|
+
"Uneven road (1 bump)", "Pass right (s)"; you will probably never need them, use the regular ones instead
|
|
123
|
+
- Most YOLO implementations scale images down before processing, so detection of small signs is difficult; depending
|
|
124
|
+
on the intended use-case of your dataset, annotating very small traffic signs might not be necessary
|
|
125
|
+
- Save changes made to the annotations by pressing "Update" in the bottom right
|
|
126
|
+
|
|
127
|
+
When done with labeling:
|
|
128
|
+
1. Go to the project page (the list of all images) and press "Export" in the top right.
|
|
129
|
+
2. Select "JSON" (should be the default) and press "Export" in the bottom left; the file should be saved to the
|
|
130
|
+
"downloads" directory and be named something like "project-1-at-2026...json"
|
|
131
|
+
|
|
132
|
+
### Export
|
|
133
|
+
|
|
134
|
+
After the verifying and correcting annotations, TSAnnotate will create train and test split, filter out background
|
|
135
|
+
images and export the data in the YOLO format for easy training. Run the following command:
|
|
136
|
+
|
|
137
|
+
`ts-annotate export /path/to/annotations.json`
|
|
138
|
+
|
|
139
|
+
Where `annotations.json` is the file exported by Label Studio.
|
|
140
|
+
|
|
141
|
+
This step requires access to the outputs generated by the "label" step. By default, they will be saved to an
|
|
142
|
+
`output` directory in the current working directory. TSAnnotate will attempt to automatically detect them. If that
|
|
143
|
+
fails, pass the path to the output using the `data_path` argument by using the same path used as `output_path` in
|
|
144
|
+
the "label" step.
|
|
145
|
+
|
|
146
|
+
The results will be saved into `output/new_dataset`. The location can be changed by using the `output_path`
|
|
147
|
+
and `name` arguments.
|
|
148
|
+
|
|
149
|
+
## Arguments
|
|
150
|
+
|
|
151
|
+
This section describes the argument that can be passed to TSAnnotate. Some of them have different meanings depending
|
|
152
|
+
on the task that is run.
|
|
153
|
+
|
|
154
|
+
### Positional Arguments
|
|
155
|
+
|
|
156
|
+
TSAnnotate expects two positional arguments:
|
|
157
|
+
|
|
158
|
+
`ts-annotate [task] [input_path]`
|
|
159
|
+
|
|
160
|
+
- task: defines the task that will be run and can be either "label" or "export"
|
|
161
|
+
- input path: path to the input data, depending on task this is either a directory or single video/image file
|
|
162
|
+
("label" task) or a JSON file ("export" task)
|
|
163
|
+
|
|
164
|
+
### Optional Arguments
|
|
165
|
+
|
|
166
|
+
The following optional arguments can be passed. Some of them are only supported in one task.
|
|
167
|
+
Run `ts-annotate --help` for details.
|
|
168
|
+
|
|
169
|
+
| Argument | Label | Export | Default |
|
|
170
|
+
| -------- | ----- | ------ | ------- |
|
|
171
|
+
|-o/--output_path | Path to save labeled images to | Path to save dataset to | output |
|
|
172
|
+
|-sr/--sample_rate | Rate at which images are sampled from videos | - | 1 |
|
|
173
|
+
|-d/--data_path | - | Path to output of "label" task | - |
|
|
174
|
+
|-ts/--test_split | - | Share of images in test split | 0.1 |
|
|
175
|
+
|-vs/--val_split | - | Share of images in validation split | 0.1 |
|
|
176
|
+
|-br/--background_ratio | - | Maximum share of background images | 0.1 |
|
|
177
|
+
|-n/--name | - | Name of dataset directory | new_dataset |
|
|
178
|
+
|-l/--labels | File with labels used for annotation | File with labels used for annotation | - |
|
|
179
|
+
|-m/--model | Model to use for labeling | - | - |
|
|
180
|
+
|-fs/--filter_similar | Remove similar consecutive images |- | - |
|
|
181
|
+
|-si/--sort_inputs | Sort inputs by numbers extracted from file names | - | - |
|
|
182
|
+
|
|
183
|
+
## Customization
|
|
184
|
+
|
|
185
|
+
This section contains more detailed explanations about the usage of some of the arguments that customize
|
|
186
|
+
the tools functions.
|
|
187
|
+
|
|
188
|
+
### Labels
|
|
189
|
+
|
|
190
|
+
The default labels used to annotate images are based on the [ETSD](https://ieeexplore.ieee.org/abstract/document/8558481) paper, expanded with some classes to
|
|
191
|
+
represent signs that were not in the original dataset. A table listing all labels can be found
|
|
192
|
+
[here](https://huggingface.co/datasets/dsilbermann/european_traffic_signs).
|
|
193
|
+
Custom labels can be used by passing a CSV file to the `labels` argument. The file should contain lines
|
|
194
|
+
of the following format:
|
|
195
|
+
|
|
196
|
+
`label,short label,color`
|
|
197
|
+
|
|
198
|
+
Where:
|
|
199
|
+
|
|
200
|
+
- *label* is the full name of the label
|
|
201
|
+
- *short label* is a more compact name for the label used to save space in the Label Studio UI; if the label
|
|
202
|
+
names are already short, it may be the same as the full label
|
|
203
|
+
- *color* is a hex color code used to highlight groups of labels in the Label Studio UI
|
|
204
|
+
|
|
205
|
+
While all of these values must be present, nothing prevents you from using the same text as *label* and
|
|
206
|
+
*short label*, or the same *color* for all labels. Do not include a header line in the file.
|
|
207
|
+
|
|
208
|
+
### Model
|
|
209
|
+
|
|
210
|
+
By default, pre-labeling is done using a YOLO26 model trained on a collection of European traffic sign
|
|
211
|
+
detection datasets, which is pulled from
|
|
212
|
+
[HuggingFace](https://huggingface.co/dsilbermann/traffic_sign_detection_europe). You can use a custom
|
|
213
|
+
model by passing it to the `model` argument. Currently, only models based on
|
|
214
|
+
[Ultralytics](https://www.ultralytics.com/) [YOLO](https://docs.ultralytics.com/models/yolo26)
|
|
215
|
+
are supported. Models can either be stored locally or on HuggingFace. In that case, repo ID and filename
|
|
216
|
+
must be passed like this: `user/repo/filename.pt`
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
TSAnnotate/Annotate.py,sha256=xXd3NqDfYUNKmXKVkeJbR8yOJ0Sc9crocNNJ3fLAWFo,1949
|
|
2
|
+
TSAnnotate/Export.py,sha256=Pnq1q9MvxB0p2SOGhJzBRfTtiHjUebeaXDCpKqB_zVU,7203
|
|
3
|
+
TSAnnotate/Filter.py,sha256=379R6jwfREYohL-i3XcVj0zDeIf0JEFZRcIOnqfmvUs,670
|
|
4
|
+
TSAnnotate/Load.py,sha256=8gm7Q1XPrsYBbqvqjHpx6vIzQBtFpCq7Ef8DPfP5aXw,3363
|
|
5
|
+
TSAnnotate/Main.py,sha256=RcqcFfYj9Arywul46XnOlZjmdF_rxHK0-Z2r2o4cSi8,8021
|
|
6
|
+
TSAnnotate/Sample.py,sha256=AuNJLChUUEs8j1TgNqrV4uFUxPYzijTGpZPR60NX_Ug,777
|
|
7
|
+
TSAnnotate/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
TSAnnotate/data/labels.csv,sha256=jWdbjIn-jByrahY8aVPR3Q4CsQoamop--2WLJzhRrrM,8098
|
|
9
|
+
tsannotate-1.0.0.dist-info/licenses/LICENSE,sha256=Z9EItb-pDTFCTki7ZbexGsknyG5u0HXrXztFPSCJ9hU,1072
|
|
10
|
+
tsannotate-1.0.0.dist-info/._entry_points.txt,sha256=09XKFD2FPzUnkJPQrd3oV8Zjq-YBVB0EMNuqwIkyfDo,163
|
|
11
|
+
tsannotate-1.0.0.dist-info/._requires.txt,sha256=09XKFD2FPzUnkJPQrd3oV8Zjq-YBVB0EMNuqwIkyfDo,163
|
|
12
|
+
tsannotate-1.0.0.dist-info/._top_level.txt,sha256=09XKFD2FPzUnkJPQrd3oV8Zjq-YBVB0EMNuqwIkyfDo,163
|
|
13
|
+
tsannotate-1.0.0.dist-info/METADATA,sha256=Vowkb8-4X0TxU5cgdcf8KQKDmNpuifQbHv68KG_oZ2o,10350
|
|
14
|
+
tsannotate-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
15
|
+
tsannotate-1.0.0.dist-info/entry_points.txt,sha256=McMqgI5YhQ1tVaD6Ckq5CaW5rJvD0ZBs0ELFD_YV970,53
|
|
16
|
+
tsannotate-1.0.0.dist-info/top_level.txt,sha256=ROlbnldcnIfacGZfIodVmAN-YxowS6MiJsbcsdwgJLM,11
|
|
17
|
+
tsannotate-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 David Silbermann
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
TSAnnotate
|