Datasets:

Languages:
English
ArXiv:
License:
eden500 commited on
Commit
3221cd8
·
verified ·
1 Parent(s): b0e2237

Upload 3 files

Browse files
Files changed (3) hide show
  1. LICENSE (1).txt +201 -0
  2. README.md +52 -3
  3. noise_annotations.py +314 -0
LICENSE (1).txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Eden Grad and Moshe Kimhi, Technion IIT.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -1,3 +1,52 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Noisy-Labels-Instance-Segmentation
2
+ ## This is the official repo for the paper A Benchmark for Learning with Noisy Labels in Instance Segmentation
3
+
4
+ ![paper meme](https://github.com/eden500/Noisy-Labels-Instance-Segmentation/assets/66938362/e786140b-cd28-41d3-8193-2529f1ed37d5)
5
+
6
+ ### ReadMe:
7
+ Important! The original annotations should be in coco format.
8
+
9
+ To run the benchmark, run the following:
10
+ ```
11
+ python noise_annotations.py /path/to/annotations --benchmark {easy, medium, hard} (choose the benchmark level) --seed 1
12
+ ```
13
+
14
+ For example:
15
+ ```
16
+ python noise_annotations.py /path/to/annotations --benchmark easy --seed 1
17
+ ```
18
+
19
+
20
+ To run a custom noise method, run the following:
21
+ ```
22
+ python noise_annotations.py /path/to/annotations --method_name method_name --corruption_values [{'rand': [scale_proportion, kernel_size(should be odd number)],'localization': [scale_proportion, std_dev], 'approximation': [scale_proportion, tolerance], 'flip_class': percent_class_noise}]}]
23
+ ```
24
+
25
+ For example:
26
+ ```
27
+ python noise_annotations.py /path/to/annotations --method_name my_noise_method --corruption_values [{'rand': [0.2, 3], 'localization': [0.2, 2], 'approximation': [0.2, 5], 'flip_class': 0.2}]
28
+ ```
29
+
30
+
31
+ ## Citation
32
+
33
+
34
+ If you use this benchmark in your research, please cite this project.
35
+
36
+
37
+ ```
38
+ Bibtex will be avalible shortly
39
+ ```
40
+
41
+
42
+ ## License
43
+
44
+ This project is released under the [Apache 2.0 license](https://github.com/eden500/Noisy-Labels-Instance-Segmentation/blob/main/LICENSE.txt).
45
+
46
+
47
+ Please make sure you use it with proper licenced Datasets.
48
+
49
+ We use [MS-COCO/LVIS](https://cocodataset.org/#termsofuse) and [Cityscapes](https://www.cityscapes-dataset.com/license/)
50
+
51
+
52
+ ![image](https://github.com/eden500/Noisy-Labels-Instance-Segmentation/assets/66938362/3e22ad79-3f12-4767-b994-2df57dd265e7)
noise_annotations.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import numpy as np
4
+ import cv2
5
+ from pycocotools.coco import COCO
6
+ from pycocotools import mask as maskUtils
7
+ from shapely.geometry import Polygon
8
+ from tqdm import tqdm
9
+ import random
10
+ import argparse
11
+
12
+
13
+ def create_single_corruption_folder_copy_file(corruption_str, original_annotations_path, method_name):
14
+ """
15
+ Creates new folders and copies the original annotation file to the new folder for later modification.
16
+ """
17
+ base_path = f'noisy_data_{method_name}/coco_ann{corruption_str}'
18
+ os.makedirs(f'{base_path}/train', exist_ok=True)
19
+ os.makedirs(f'{base_path}/val', exist_ok=True)
20
+
21
+ for split in ['train', 'val']:
22
+ original_annotation_path = f'{original_annotations_path}/instances_{split}2017.json'
23
+ destination_path = f'{base_path}/{split}'
24
+ os.system(f'cp {original_annotation_path} {destination_path}')
25
+
26
+ print(f'Created folder and copied annotation file for {corruption_str}')
27
+
28
+
29
+ def create_new_folders_and_copy_files(original_annotations_path, method_name, corruption_distances):
30
+ """
31
+ Creates new folders and copies files for the corrupted dataset.
32
+ """
33
+ name_to_add = f'_{method_name}_'
34
+
35
+ for corruption_d in corruption_distances:
36
+ if isinstance(corruption_d, dict):
37
+ corruption_str = name_to_add + '_'.join(f'{k}_{str(v).replace(" ", "")}' for k, v in corruption_d.items()) + '_'
38
+ else:
39
+ corruption_str = name_to_add + str(corruption_d)
40
+
41
+ create_single_corruption_folder_copy_file(corruption_str, original_annotations_path, method_name)
42
+
43
+ def pick_noise(probabilities):
44
+ # Calculate the remaining probability for no noise.
45
+ remaining_probability = 1 - sum(p[0] for p in probabilities.values())
46
+ probabilities['none'] = [remaining_probability, None]
47
+
48
+ keys = list(probabilities.keys())
49
+ probs = [probabilities[key][0] for key in keys]
50
+ chosen_key = random.choices(keys, weights=probs, k=1)[0]
51
+ return chosen_key, probabilities[chosen_key][1]
52
+
53
+
54
+ def new_boundaries_with_prob(d, coco, ann_id, file, annotation):
55
+ """
56
+ Modifies the boundaries of an annotation with a given probability.
57
+ """
58
+ current_ann = coco.loadAnns(ann_id)[0]
59
+ mask = coco.annToMask(current_ann)
60
+
61
+ changed_class = False
62
+ if 'flip_class' in d:
63
+ boundary_ver = 'flip_class'
64
+ cat_to_index_dict, index_to_cat_dict = get_index_cat_dicts(file)
65
+ num_classes = get_num_classes(file)
66
+ percent_noise = d.pop('flip_class')
67
+ C = uniform_mix_C(percent_noise, num_classes) if boundary_ver == 'flip_class'\
68
+ else uniform_assymetric_mix_C(percent_noise, file, cat_to_index_dict, num_classes) # to support assym later
69
+ change_category_with_confusion_matrix_single(annotation, C, cat_to_index_dict, index_to_cat_dict)
70
+ changed_class = annotation['category_id'] != current_ann['category_id']
71
+
72
+ noise_type, k = pick_noise(d)
73
+
74
+ if noise_type == 'rand':
75
+ kernel = np.ones((k, k), np.uint8)
76
+ new_mask = cv2.dilate(mask, kernel, iterations=1) if np.random.rand() < 0.5 else cv2.erode(mask, kernel, iterations=1)
77
+ elif noise_type == 'localization':
78
+ new_mask = add_localization_noise(mask, k)
79
+ elif noise_type == 'approximation':
80
+ new_mask = add_approximation_noise(mask, k)
81
+ elif noise_type == 'none':
82
+ new_mask = mask
83
+ else:
84
+ raise ValueError(f'Unknown boundary version: {noise_type}')
85
+
86
+ # Convert modified mask back to RLE
87
+ rle_modified = maskUtils.encode(np.asfortranarray(new_mask))
88
+ rle_modified['counts'] = rle_modified['counts'].decode('utf-8') if isinstance(rle_modified['counts'], bytes) else rle_modified['counts']
89
+
90
+ return rle_modified, noise_type, changed_class
91
+
92
+
93
+ def change_boundaries_for_file(file, coco, d, seed=1):
94
+ """
95
+ Changes the boundaries for all annotations in a given file.
96
+ """
97
+ if seed is not None:
98
+ np.random.seed(seed)
99
+
100
+ for annotation in tqdm(file['annotations']):
101
+ new_mask, chosen_type, class_noise = new_boundaries_with_prob(d.copy(), coco, annotation['id'], file, annotation)
102
+ if chosen_type != 'none':
103
+ annotation['boundary_type'] = chosen_type
104
+ annotation['segmentation'] = new_mask
105
+ else:
106
+ annotation['boundary_type'] = 'none'
107
+ if class_noise:
108
+ annotation['class_noise'] = True
109
+ else:
110
+ annotation['class_noise'] = False
111
+
112
+
113
+ def noise_annotations(method_name, corruption_distances, seed=1):
114
+ """
115
+ Adds noise to the annotations.
116
+ """
117
+ first_dir = f'noisy_data_{method_name}'
118
+ name_to_add = f'_{method_name}_'
119
+
120
+ for corruption_d in corruption_distances:
121
+ corruption_str = name_to_add + ('_'.join(f'{k}_{str(v).replace(" ", "")}' for k, v in corruption_d.items()) + '_' if isinstance(corruption_d, dict) else str(corruption_d))
122
+
123
+ for split in ['train', 'val']:
124
+ with open(f'{first_dir}/coco_ann{corruption_str}/{split}/instances_{split}2017.json') as f:
125
+ ann = json.load(f)
126
+
127
+ coco = COCO(f'{first_dir}/coco_ann{corruption_str}/{split}/instances_{split}2017.json')
128
+ change_boundaries_for_file(ann, coco, corruption_d, seed)
129
+
130
+ with open(f'{first_dir}/coco_ann{corruption_str}/{split}/instances_{split}2017.json', 'w') as f:
131
+ json.dump(ann, f)
132
+
133
+ print(f'Finished {corruption_str}')
134
+
135
+
136
+ def mask_to_polygon(mask):
137
+ """
138
+ Converts a mask to a polygon.
139
+ """
140
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
141
+ return [contour[:, 0, :] for contour in contours] if contours else []
142
+
143
+
144
+ def polygon_to_mask(polygon, h, w):
145
+ """
146
+ Converts a polygon to a mask.
147
+ """
148
+ mask = np.zeros((h, w), dtype=np.uint8)
149
+ cv2.fillPoly(mask, [polygon], 1)
150
+ return mask
151
+
152
+
153
+ def add_gaussian_noise(vertices, mean=0, std_dev=1):
154
+ """
155
+ Adds Gaussian noise to each vertex in a polygon.
156
+ """
157
+ noise = np.random.normal(mean, std_dev, vertices.shape)
158
+ return np.round(vertices + noise).astype(int)
159
+
160
+
161
+ def add_localization_noise(mask, std_dev=1):
162
+ """
163
+ Adds Gaussian noise to the vertices of the polygon.
164
+ """
165
+ if np.sum(mask) == 0:
166
+ return mask
167
+
168
+ final_mask_noisy = np.zeros(mask.shape, dtype=np.uint8)
169
+ for polygon in mask_to_polygon(mask):
170
+ vertices_noisy = add_gaussian_noise(polygon, std_dev=std_dev)
171
+ final_mask_noisy = np.maximum(final_mask_noisy, polygon_to_mask(vertices_noisy, mask.shape[0], mask.shape[1]))
172
+
173
+ return final_mask_noisy
174
+
175
+
176
+ def simplify_polygon(polygon, tolerance):
177
+ """
178
+ Simplifies the polygon by removing vertices.
179
+ """
180
+ if len(polygon) < 4:
181
+ return None
182
+
183
+ shapely_polygon = Polygon(polygon)
184
+ return shapely_polygon.simplify(tolerance, preserve_topology=True)
185
+
186
+
187
+ def simplified_polygon_to_mask(simplified_polygon, h, w):
188
+ """
189
+ Converts a simplified polygon back to a mask.
190
+ """
191
+ new_mask = np.zeros((h, w), dtype=np.uint8)
192
+ simplified_coords = np.array(simplified_polygon.exterior.coords).reshape((-1, 1, 2))
193
+ cv2.fillPoly(new_mask, [simplified_coords.astype(np.int32)], color=(1))
194
+ return new_mask
195
+
196
+
197
+ def add_approximation_noise(mask, tolerance):
198
+ """
199
+ Adds noise to the vertices of the polygon by simplifying it.
200
+ """
201
+ if np.sum(mask) == 0:
202
+ return mask
203
+
204
+ final_mask_noisy = np.zeros(mask.shape, dtype=np.uint8)
205
+ for polygon in mask_to_polygon(mask):
206
+ simplified_polygon = simplify_polygon(polygon, tolerance)
207
+ if simplified_polygon is None:
208
+ continue
209
+ mask_noisy = simplified_polygon_to_mask(simplified_polygon, mask.shape[0], mask.shape[1])
210
+ final_mask_noisy = np.maximum(final_mask_noisy, mask_noisy)
211
+
212
+ return final_mask_noisy
213
+
214
+
215
+ def change_category_with_confusion_matrix_single(annotation, C, cat_to_index_dict, index_to_cat_dict):
216
+ """
217
+ Changes the category_id of an annotation based on a confusion matrix.
218
+ """
219
+ chosen_index = np.random.choice(np.arange(C.shape[1]), p=C[cat_to_index_dict[annotation['category_id']]])
220
+ annotation['category_id'] = index_to_cat_dict[chosen_index]
221
+
222
+
223
+ def get_index_cat_dicts(ann):
224
+ """
225
+ Returns dictionaries mapping category_id to index and vice versa.
226
+ """
227
+ cat_to_index_dict = {cat_info['id']: i for i, cat_info in enumerate(ann['categories'])}
228
+ index_to_cat_dict = {i: cat_info['id'] for i, cat_info in enumerate(ann['categories'])}
229
+ return cat_to_index_dict, index_to_cat_dict
230
+
231
+
232
+ def get_num_classes(ann):
233
+ """
234
+ Returns the number of classes in the dataset.
235
+ """
236
+ return len(ann['categories'])
237
+
238
+
239
+ def uniform_mix_C(mixing_ratio, num_classes):
240
+ """
241
+ Returns a linear interpolation of a uniform matrix and an identity matrix.
242
+ """
243
+ return mixing_ratio * np.full((num_classes, num_classes), 1 / num_classes) + (1 - mixing_ratio) * np.eye(num_classes)
244
+
245
+
246
+ def uniform_assymetric_mix_C(mixing_ratio, ann, cat_to_index_dict, num_classes):
247
+ """
248
+ Returns a matrix with (1 - corruption_prob) on the diagonals, and corruption_prob
249
+ concentrated in only one other entry for each row.
250
+ """
251
+ subcat_dict = {cat_info['supercategory']: [] for cat_info in ann['categories']}
252
+ for cat_info in ann['categories']:
253
+ subcat_dict[cat_info['supercategory']].append(cat_to_index_dict[cat_info['id']])
254
+
255
+ C = np.zeros((num_classes, num_classes))
256
+ for i in range(num_classes):
257
+ C[i][subcat_dict[ann['categories'][i]['supercategory']]] = mixing_ratio * 1 / len(subcat_dict[ann['categories'][i]['supercategory']])
258
+ C[i][i] += 1 - mixing_ratio
259
+ return C
260
+
261
+
262
+ def argument_parser():
263
+ parser = argparse.ArgumentParser()
264
+ parser.add_argument('annotations_path', type=str, help='The path to the original annotations')
265
+ parser.add_argument('--method_name', type=str, default='custom_method', help='The name of the method to be used for the corruption')
266
+ parser.add_argument('--benchmark', type=str, default='', help='The benchmark to be used for the corruption')
267
+ parser.add_argument('--corruption_values', type=list, default=[{'rand': [1, 3]}], help='The values to be used for the corruption')
268
+ parser.add_argument('--seed', type=int, default=1, help='The seed to be used for the random noise')
269
+ return parser.parse_args()
270
+
271
+
272
+ if __name__ == '__main__':
273
+ args = argument_parser()
274
+
275
+ Benchmarks = {
276
+ 'easy':
277
+ {'approximation': [0.2, 5], 'localization': [0.2, 2], 'rand': [0.2, 3], 'flip_class': 0.2},
278
+ 'medium':
279
+ {'approximation': [0.25, 10], 'localization': [0.25, 3], 'rand': [0.25, 5], 'flip_class': 0.3},
280
+ 'hard':
281
+ {'approximation': [0.3, 15], 'localization': [0.3, 4], 'rand': [0.3, 7], 'flip_class': 0.4}
282
+ }
283
+
284
+ original_annotations_path = args.annotations_path
285
+ corruption_values = args.corruption_values
286
+ if args.benchmark:
287
+ corruption_values = Benchmarks[args.benchmark]
288
+
289
+ method_name = args.method_name
290
+ if args.benchmark:
291
+ method_name = args.benchmark
292
+
293
+ create_new_folders_and_copy_files(original_annotations_path, method_name, corruption_values)
294
+ noise_annotations(method_name, corruption_values, seed=args.seed)
295
+
296
+
297
+ # read me:
298
+
299
+ # To run the benchmark, run the following:
300
+ # python noise_annotations.py /path/to/annotations --benchmark {easy, medium, hard} (choose one of the three) --seed 1
301
+
302
+ # To run a custom noise method, run the following:
303
+ # python noise_annotations.py /path/to/annotations --method_name method_name
304
+ # --corruption_values [{'rand': [scale_proportion, kernel_size(should be odd number)],
305
+ # 'localization': [scale_proportion, std_dev],
306
+ # 'approximation': [scale_proportion, tolerance], 'flip_class': percent_class_noise}]}]
307
+ #
308
+ # for example:
309
+ # python noise_annotations.py /path/to/annotations --method_name my_noise_method
310
+ # --corruption_values [{'rand': [0.2, 3], 'localization': [0.2, 2], 'approximation': [0.2, 5], 'flip_class': 0.2}]
311
+ #
312
+ # The script will create new folders and copy the original annotation files to the new folders. (the original annotations should be in coco format)
313
+ # It will then add noise to the annotations in the new folders based on the specified corruption values.
314
+ # The seed can be specified to ensure reproducibility.