TSAnnotate 1.0.0__tar.gz

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.
@@ -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,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,193 @@
1
+ # TSAnnotate - Fast Traffic Sign Annotation
2
+
3
+ This tool supports the creation of traffic sign detection and recognition datasets by leveraging pre-trained
4
+ models to annotate traffic scenes from videos or images. It processes videos and images and exports the
5
+ pre-labeled scenes to [Label Studio](https://labelstud.io/) for manual verification and correction.
6
+
7
+ ## Installation
8
+
9
+ 1. If not already available on your system, install FFmpeg
10
+ 2. Python 3.10 or newer is required
11
+ 3. Install from PyPI using `pip install TSAnnotate`
12
+ 4. Install Label Studio using `pip install label-studio`
13
+
14
+ ## Workflow
15
+
16
+ The workflow for creating traffic sign detection and recognition datasets using TSAnnotate and Label Studio
17
+ is the following:
18
+ 1. Collect: obtain traffic scene data as videos or images
19
+ 2. Label: pre-label traffic scenes with TSAnnotate; videos are sampled at the given rate and images are
20
+ processed as they are
21
+ 3. Verify: manually check and correct the labels using Label Studio
22
+ 4. Export: TSAnnotate creates train/test splits, filters out background images and converts annotations into
23
+ the YOLO format
24
+
25
+ ## How to use
26
+
27
+ This section contains detailed information on each step.
28
+
29
+ ### Data Collection
30
+
31
+ TSAnnotate can read either individual files or entire directories. In case of directories, all subdirectories will
32
+ be recursively searched for image and video files. The following file formats are supported:
33
+ - Videos: mov, mp4
34
+ - Images: jpg, jpeg, png
35
+
36
+ Unsupported files will be ignored, if the given input is a directory, or cause an exception, if the file is the
37
+ only input.
38
+
39
+ ### Label
40
+
41
+ Run the following command to start pre-labeling:
42
+
43
+ `ts-annotate label /path/to/input`
44
+
45
+ Replace `/path/to/input` with the path to your input file or directory. The labeled images are exported to
46
+ an `output` directory in the current working directory. See the Arguments section on how to change this, and
47
+ other default behaviors. Annotations are stored in the Label Studio specific [format](https://labelstud.io/guide/task_format).
48
+
49
+ ### Verify
50
+
51
+ Verification and correction is done manually in Label Studio. To enable import of local files to Label Studio,
52
+ run
53
+
54
+ ```
55
+ export LABEL_STUDIO_LOCAL_FILES_SERVING_ENABLED=true
56
+ export LABEL_STUDIO_LOCAL_FILES_DOCUMENT_ROOT="/path/to/output"
57
+ ```
58
+
59
+ If you are using Windows the commands are different, please ask an LLM of your choice how to do this.
60
+ Replace `/path/to/output` with the output directory of the previous step. This must be done every time
61
+ Label Studio is started. Then run Label Studio:
62
+
63
+ `label-studio start`
64
+
65
+ Label Studio should automatically open in your browser, otherwise visit `http://localhost:8080` and follow these steps:
66
+ 1. Create an account and sign in
67
+ 2. Create a new project
68
+ 3. Enter a name for the project
69
+ 4. Go to the "Labeling setup" tab at the top of the window.
70
+ 5. Select "object detection with bounding boxes"
71
+ 6. On the left side, under "Labeling Interface", switch to the "Code" tab
72
+ 7. Replace the entire content of the text box with the content of "labeling_interface.html" generated by
73
+ TSAnnotate in the output directory
74
+ 8. Press "Save" in the top right. **Do not import any data yet.**
75
+ 9. Press "Connect cloud storage"
76
+ 10. Select "Local files" and press "Next"
77
+ 11. Chose a "Storage Title" for this connection, e.g., "Images" as this is the image import
78
+ 12. Point "Absolute local path" to the "images" directory inside the output generated by TSAnnotate,
79
+ e.g., `/path/to/output/images`
80
+ 13. Optional: press "Test connection" to make sure the path was entered correctly
81
+ 14. Press "Next"
82
+ 15. Don't change anything on this page and press "Next"
83
+ 16. Press "Save". **Do not press "Save & Sync".**
84
+ 17. The same process is now repeated to import the annotations. Press "Add Source Storage"
85
+ 18. Select "Local files" and press "Next"
86
+ 19. Chose a "Storage Title", e.g., "Annotations"
87
+ 20. Point "Absolute local path" to the "annotations" directory inside the output, e.g., `/path/to/output/annotations`
88
+ 21. Optional: test the connection
89
+ 22. Press "Next"
90
+ 23. Don't change anything on this page and press "Next"
91
+ 24. Press "Save & Sync", depending on the amount of images this may take a while
92
+
93
+ 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
94
+ select images. Some notes on using Label Studio:
95
+ - Remove duplicate/similar images directly from the list by marking them using the checkbox in the first column
96
+ and selecting "Delete Tasks" from the drop-down menu above
97
+ - Labels are based on the [ETSD](https://ieeexplore.ieee.org/abstract/document/8558481), some of them are "special"
98
+ versions of regular signs: "Cyclists-Pedestrians (s)", "Cycle track (s)", "Cyclists entering or crossing (s)",
99
+ "Uneven road (1 bump)", "Pass right (s)"; you will probably never need them, use the regular ones instead
100
+ - Most YOLO implementations scale images down before processing, so detection of small signs is difficult; depending
101
+ on the intended use-case of your dataset, annotating very small traffic signs might not be necessary
102
+ - Save changes made to the annotations by pressing "Update" in the bottom right
103
+
104
+ When done with labeling:
105
+ 1. Go to the project page (the list of all images) and press "Export" in the top right.
106
+ 2. Select "JSON" (should be the default) and press "Export" in the bottom left; the file should be saved to the
107
+ "downloads" directory and be named something like "project-1-at-2026...json"
108
+
109
+ ### Export
110
+
111
+ After the verifying and correcting annotations, TSAnnotate will create train and test split, filter out background
112
+ images and export the data in the YOLO format for easy training. Run the following command:
113
+
114
+ `ts-annotate export /path/to/annotations.json`
115
+
116
+ Where `annotations.json` is the file exported by Label Studio.
117
+
118
+ This step requires access to the outputs generated by the "label" step. By default, they will be saved to an
119
+ `output` directory in the current working directory. TSAnnotate will attempt to automatically detect them. If that
120
+ fails, pass the path to the output using the `data_path` argument by using the same path used as `output_path` in
121
+ the "label" step.
122
+
123
+ The results will be saved into `output/new_dataset`. The location can be changed by using the `output_path`
124
+ and `name` arguments.
125
+
126
+ ## Arguments
127
+
128
+ This section describes the argument that can be passed to TSAnnotate. Some of them have different meanings depending
129
+ on the task that is run.
130
+
131
+ ### Positional Arguments
132
+
133
+ TSAnnotate expects two positional arguments:
134
+
135
+ `ts-annotate [task] [input_path]`
136
+
137
+ - task: defines the task that will be run and can be either "label" or "export"
138
+ - input path: path to the input data, depending on task this is either a directory or single video/image file
139
+ ("label" task) or a JSON file ("export" task)
140
+
141
+ ### Optional Arguments
142
+
143
+ The following optional arguments can be passed. Some of them are only supported in one task.
144
+ Run `ts-annotate --help` for details.
145
+
146
+ | Argument | Label | Export | Default |
147
+ | -------- | ----- | ------ | ------- |
148
+ |-o/--output_path | Path to save labeled images to | Path to save dataset to | output |
149
+ |-sr/--sample_rate | Rate at which images are sampled from videos | - | 1 |
150
+ |-d/--data_path | - | Path to output of "label" task | - |
151
+ |-ts/--test_split | - | Share of images in test split | 0.1 |
152
+ |-vs/--val_split | - | Share of images in validation split | 0.1 |
153
+ |-br/--background_ratio | - | Maximum share of background images | 0.1 |
154
+ |-n/--name | - | Name of dataset directory | new_dataset |
155
+ |-l/--labels | File with labels used for annotation | File with labels used for annotation | - |
156
+ |-m/--model | Model to use for labeling | - | - |
157
+ |-fs/--filter_similar | Remove similar consecutive images |- | - |
158
+ |-si/--sort_inputs | Sort inputs by numbers extracted from file names | - | - |
159
+
160
+ ## Customization
161
+
162
+ This section contains more detailed explanations about the usage of some of the arguments that customize
163
+ the tools functions.
164
+
165
+ ### Labels
166
+
167
+ 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
168
+ represent signs that were not in the original dataset. A table listing all labels can be found
169
+ [here](https://huggingface.co/datasets/dsilbermann/european_traffic_signs).
170
+ Custom labels can be used by passing a CSV file to the `labels` argument. The file should contain lines
171
+ of the following format:
172
+
173
+ `label,short label,color`
174
+
175
+ Where:
176
+
177
+ - *label* is the full name of the label
178
+ - *short label* is a more compact name for the label used to save space in the Label Studio UI; if the label
179
+ names are already short, it may be the same as the full label
180
+ - *color* is a hex color code used to highlight groups of labels in the Label Studio UI
181
+
182
+ While all of these values must be present, nothing prevents you from using the same text as *label* and
183
+ *short label*, or the same *color* for all labels. Do not include a header line in the file.
184
+
185
+ ### Model
186
+
187
+ By default, pre-labeling is done using a YOLO26 model trained on a collection of European traffic sign
188
+ detection datasets, which is pulled from
189
+ [HuggingFace](https://huggingface.co/dsilbermann/traffic_sign_detection_europe). You can use a custom
190
+ model by passing it to the `model` argument. Currently, only models based on
191
+ [Ultralytics](https://www.ultralytics.com/) [YOLO](https://docs.ultralytics.com/models/yolo26)
192
+ are supported. Models can either be stored locally or on HuggingFace. In that case, repo ID and filename
193
+ must be passed like this: `user/repo/filename.pt`
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "TSAnnotate"
7
+ version = "1.0.0"
8
+ authors = [
9
+ { name="David Silbermann", email="david.silbermann@rub.de" },
10
+ ]
11
+ description = "Quickly annotate images for traffic sign detection and recognition by using pre-trained models."
12
+ readme = "README.md"
13
+ requires-python = ">=3.10"
14
+ dependencies = [
15
+ "torch>=2.14.1",
16
+ "torchvision>=0.29.1",
17
+ "torchcodec>=0.16.0",
18
+ "ultralytics>=8.4.190",
19
+ "pillow>=12.3.0",
20
+ "scikit-image>=0.25.2",
21
+ "opencv-python>=4.11.0.86",
22
+ "huggingface-hub>=2.4.0"
23
+ ]
24
+ classifiers = [
25
+ "Programming Language :: Python :: 3",
26
+ "Operating System :: OS Independent",
27
+ ]
28
+ license = "MIT"
29
+ license-files = ["LICEN[CS]E*"]
30
+
31
+ [project.scripts]
32
+ ts-annotate = "TSAnnotate.Main:main"
33
+
34
+ [tool.setuptools.package-data]
35
+ TSAnnotate = ["data/*"]
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/d-silbermann/TSAnnotate"
39
+ Issues = "https://github.com/d-silbermann/TSAnnotate/issues"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
@@ -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