megadetector 10.0.13__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.

Potentially problematic release.


This version of megadetector might be problematic. Click here for more details.

Files changed (147) hide show
  1. megadetector/__init__.py +0 -0
  2. megadetector/api/__init__.py +0 -0
  3. megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
  4. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
  5. megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
  6. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +125 -0
  7. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
  8. megadetector/classification/__init__.py +0 -0
  9. megadetector/classification/aggregate_classifier_probs.py +108 -0
  10. megadetector/classification/analyze_failed_images.py +227 -0
  11. megadetector/classification/cache_batchapi_outputs.py +198 -0
  12. megadetector/classification/create_classification_dataset.py +626 -0
  13. megadetector/classification/crop_detections.py +516 -0
  14. megadetector/classification/csv_to_json.py +226 -0
  15. megadetector/classification/detect_and_crop.py +853 -0
  16. megadetector/classification/efficientnet/__init__.py +9 -0
  17. megadetector/classification/efficientnet/model.py +415 -0
  18. megadetector/classification/efficientnet/utils.py +608 -0
  19. megadetector/classification/evaluate_model.py +520 -0
  20. megadetector/classification/identify_mislabeled_candidates.py +152 -0
  21. megadetector/classification/json_to_azcopy_list.py +63 -0
  22. megadetector/classification/json_validator.py +696 -0
  23. megadetector/classification/map_classification_categories.py +276 -0
  24. megadetector/classification/merge_classification_detection_output.py +509 -0
  25. megadetector/classification/prepare_classification_script.py +194 -0
  26. megadetector/classification/prepare_classification_script_mc.py +228 -0
  27. megadetector/classification/run_classifier.py +287 -0
  28. megadetector/classification/save_mislabeled.py +110 -0
  29. megadetector/classification/train_classifier.py +827 -0
  30. megadetector/classification/train_classifier_tf.py +725 -0
  31. megadetector/classification/train_utils.py +323 -0
  32. megadetector/data_management/__init__.py +0 -0
  33. megadetector/data_management/animl_to_md.py +161 -0
  34. megadetector/data_management/annotations/__init__.py +0 -0
  35. megadetector/data_management/annotations/annotation_constants.py +33 -0
  36. megadetector/data_management/camtrap_dp_to_coco.py +270 -0
  37. megadetector/data_management/cct_json_utils.py +566 -0
  38. megadetector/data_management/cct_to_md.py +184 -0
  39. megadetector/data_management/cct_to_wi.py +293 -0
  40. megadetector/data_management/coco_to_labelme.py +284 -0
  41. megadetector/data_management/coco_to_yolo.py +702 -0
  42. megadetector/data_management/databases/__init__.py +0 -0
  43. megadetector/data_management/databases/add_width_and_height_to_db.py +107 -0
  44. megadetector/data_management/databases/combine_coco_camera_traps_files.py +210 -0
  45. megadetector/data_management/databases/integrity_check_json_db.py +528 -0
  46. megadetector/data_management/databases/subset_json_db.py +195 -0
  47. megadetector/data_management/generate_crops_from_cct.py +200 -0
  48. megadetector/data_management/get_image_sizes.py +164 -0
  49. megadetector/data_management/labelme_to_coco.py +559 -0
  50. megadetector/data_management/labelme_to_yolo.py +349 -0
  51. megadetector/data_management/lila/__init__.py +0 -0
  52. megadetector/data_management/lila/create_lila_blank_set.py +556 -0
  53. megadetector/data_management/lila/create_lila_test_set.py +187 -0
  54. megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
  55. megadetector/data_management/lila/download_lila_subset.py +182 -0
  56. megadetector/data_management/lila/generate_lila_per_image_labels.py +777 -0
  57. megadetector/data_management/lila/get_lila_annotation_counts.py +174 -0
  58. megadetector/data_management/lila/get_lila_image_counts.py +112 -0
  59. megadetector/data_management/lila/lila_common.py +319 -0
  60. megadetector/data_management/lila/test_lila_metadata_urls.py +164 -0
  61. megadetector/data_management/mewc_to_md.py +344 -0
  62. megadetector/data_management/ocr_tools.py +873 -0
  63. megadetector/data_management/read_exif.py +964 -0
  64. megadetector/data_management/remap_coco_categories.py +195 -0
  65. megadetector/data_management/remove_exif.py +156 -0
  66. megadetector/data_management/rename_images.py +194 -0
  67. megadetector/data_management/resize_coco_dataset.py +663 -0
  68. megadetector/data_management/speciesnet_to_md.py +41 -0
  69. megadetector/data_management/wi_download_csv_to_coco.py +247 -0
  70. megadetector/data_management/yolo_output_to_md_output.py +594 -0
  71. megadetector/data_management/yolo_to_coco.py +876 -0
  72. megadetector/data_management/zamba_to_md.py +188 -0
  73. megadetector/detection/__init__.py +0 -0
  74. megadetector/detection/change_detection.py +840 -0
  75. megadetector/detection/process_video.py +479 -0
  76. megadetector/detection/pytorch_detector.py +1451 -0
  77. megadetector/detection/run_detector.py +1267 -0
  78. megadetector/detection/run_detector_batch.py +2159 -0
  79. megadetector/detection/run_inference_with_yolov5_val.py +1314 -0
  80. megadetector/detection/run_md_and_speciesnet.py +1494 -0
  81. megadetector/detection/run_tiled_inference.py +1038 -0
  82. megadetector/detection/tf_detector.py +209 -0
  83. megadetector/detection/video_utils.py +1379 -0
  84. megadetector/postprocessing/__init__.py +0 -0
  85. megadetector/postprocessing/add_max_conf.py +72 -0
  86. megadetector/postprocessing/categorize_detections_by_size.py +166 -0
  87. megadetector/postprocessing/classification_postprocessing.py +1752 -0
  88. megadetector/postprocessing/combine_batch_outputs.py +249 -0
  89. megadetector/postprocessing/compare_batch_results.py +2110 -0
  90. megadetector/postprocessing/convert_output_format.py +403 -0
  91. megadetector/postprocessing/create_crop_folder.py +629 -0
  92. megadetector/postprocessing/detector_calibration.py +570 -0
  93. megadetector/postprocessing/generate_csv_report.py +522 -0
  94. megadetector/postprocessing/load_api_results.py +223 -0
  95. megadetector/postprocessing/md_to_coco.py +428 -0
  96. megadetector/postprocessing/md_to_labelme.py +351 -0
  97. megadetector/postprocessing/md_to_wi.py +41 -0
  98. megadetector/postprocessing/merge_detections.py +392 -0
  99. megadetector/postprocessing/postprocess_batch_results.py +2077 -0
  100. megadetector/postprocessing/remap_detection_categories.py +226 -0
  101. megadetector/postprocessing/render_detection_confusion_matrix.py +677 -0
  102. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +206 -0
  103. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +82 -0
  104. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1665 -0
  105. megadetector/postprocessing/separate_detections_into_folders.py +795 -0
  106. megadetector/postprocessing/subset_json_detector_output.py +964 -0
  107. megadetector/postprocessing/top_folders_to_bottom.py +238 -0
  108. megadetector/postprocessing/validate_batch_results.py +332 -0
  109. megadetector/taxonomy_mapping/__init__.py +0 -0
  110. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
  111. megadetector/taxonomy_mapping/map_new_lila_datasets.py +213 -0
  112. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +165 -0
  113. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +543 -0
  114. megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
  115. megadetector/taxonomy_mapping/simple_image_download.py +224 -0
  116. megadetector/taxonomy_mapping/species_lookup.py +1008 -0
  117. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
  118. megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
  119. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
  120. megadetector/tests/__init__.py +0 -0
  121. megadetector/tests/test_nms_synthetic.py +335 -0
  122. megadetector/utils/__init__.py +0 -0
  123. megadetector/utils/ct_utils.py +1857 -0
  124. megadetector/utils/directory_listing.py +199 -0
  125. megadetector/utils/extract_frames_from_video.py +307 -0
  126. megadetector/utils/gpu_test.py +125 -0
  127. megadetector/utils/md_tests.py +2072 -0
  128. megadetector/utils/path_utils.py +2832 -0
  129. megadetector/utils/process_utils.py +172 -0
  130. megadetector/utils/split_locations_into_train_val.py +237 -0
  131. megadetector/utils/string_utils.py +234 -0
  132. megadetector/utils/url_utils.py +825 -0
  133. megadetector/utils/wi_platform_utils.py +968 -0
  134. megadetector/utils/wi_taxonomy_utils.py +1759 -0
  135. megadetector/utils/write_html_image_list.py +239 -0
  136. megadetector/visualization/__init__.py +0 -0
  137. megadetector/visualization/plot_utils.py +309 -0
  138. megadetector/visualization/render_images_with_thumbnails.py +243 -0
  139. megadetector/visualization/visualization_utils.py +1940 -0
  140. megadetector/visualization/visualize_db.py +630 -0
  141. megadetector/visualization/visualize_detector_output.py +479 -0
  142. megadetector/visualization/visualize_video_output.py +705 -0
  143. megadetector-10.0.13.dist-info/METADATA +134 -0
  144. megadetector-10.0.13.dist-info/RECORD +147 -0
  145. megadetector-10.0.13.dist-info/WHEEL +5 -0
  146. megadetector-10.0.13.dist-info/licenses/LICENSE +19 -0
  147. megadetector-10.0.13.dist-info/top_level.txt +1 -0
@@ -0,0 +1,559 @@
1
+ """
2
+
3
+ labelme_to_coco.py
4
+
5
+ Converts a folder of labelme-formatted .json files to COCO.
6
+
7
+ """
8
+
9
+ #%% Constants and imports
10
+
11
+ import os
12
+ import sys
13
+ import json
14
+ import uuid
15
+ import argparse
16
+
17
+ from multiprocessing.pool import Pool, ThreadPool
18
+ from functools import partial
19
+ from tqdm import tqdm
20
+
21
+ from megadetector.utils import path_utils
22
+ from megadetector.visualization.visualization_utils import open_image
23
+
24
+
25
+ #%% Support functions
26
+
27
+ def _add_category(category_name,category_name_to_id,candidate_category_id=0):
28
+ """
29
+ Adds the category [category_name] to the dict [category_name_to_id], by default
30
+ using the next available integer index.
31
+ """
32
+
33
+ if category_name in category_name_to_id:
34
+ return category_name_to_id[category_name]
35
+ while candidate_category_id in category_name_to_id.values():
36
+ candidate_category_id += 1
37
+ category_name_to_id[category_name] = candidate_category_id
38
+ return candidate_category_id
39
+
40
+
41
+ def _process_labelme_file(image_fn_relative,input_folder,use_folders_as_labels,
42
+ no_json_handling,validate_image_sizes,
43
+ category_name_to_id,allow_new_categories=True):
44
+ """
45
+ Internal function for processing each image; this support function facilitates parallelization.
46
+ """
47
+
48
+ result = {}
49
+ result['im'] = None
50
+ result['annotations_this_image'] = None
51
+ result['status'] = None
52
+
53
+ image_fn_abs = os.path.join(input_folder,image_fn_relative)
54
+ json_fn_abs = os.path.splitext(image_fn_abs)[0] + '.json'
55
+
56
+ im = {}
57
+ im['id'] = image_fn_relative
58
+ im['file_name'] = image_fn_relative
59
+
60
+ # If there's no .json file for this image...
61
+ if not os.path.isfile(json_fn_abs):
62
+
63
+ # Either skip it...
64
+ if no_json_handling == 'skip':
65
+ print('Skipping image {} (no .json file)'.format(image_fn_relative))
66
+ result['status'] = 'skipped (no .json file)'
67
+ return result
68
+
69
+ # ...or error
70
+ elif no_json_handling == 'error':
71
+ raise ValueError('Image file {} has no corresponding .json file'.format(
72
+ image_fn_relative))
73
+
74
+ # ...or treat it as empty.
75
+ elif no_json_handling == 'empty':
76
+ try:
77
+ pil_im = open_image(image_fn_abs)
78
+ except Exception:
79
+ print('Warning: error opening image {}, skipping'.format(image_fn_abs))
80
+ result['status'] = 'image load error'
81
+ return result
82
+ im['width'] = pil_im.width
83
+ im['height'] = pil_im.height
84
+
85
+ # Just in case we need to differentiate between "no .json file" and "a .json file with no annotations"
86
+ im['no_labelme_json'] = True
87
+ shapes = []
88
+ else:
89
+ raise ValueError('Unrecognized specifier {} for handling images with no .json files'.format(
90
+ no_json_handling))
91
+
92
+ # If we found a .json file for this image...
93
+ else:
94
+
95
+ # Read the .json file
96
+ with open(json_fn_abs,'r') as f:
97
+ labelme_data = json.load(f)
98
+ im['width'] = labelme_data['imageWidth']
99
+ im['height'] = labelme_data['imageHeight']
100
+
101
+ if validate_image_sizes:
102
+ try:
103
+ pil_im = open_image(image_fn_abs)
104
+ except Exception:
105
+ print('Warning: error opening image {} for size validation, skipping'.format(image_fn_abs))
106
+ result['status'] = 'skipped (size validation error)'
107
+ return result
108
+ if not (im['width'] == pil_im.width and im['height'] == pil_im.height):
109
+ print('Warning: image size validation error for file {}'.format(image_fn_relative))
110
+ im['width'] = pil_im.width
111
+ im['height'] = pil_im.height
112
+ im['labelme_width'] = labelme_data['imageWidth']
113
+ im['labelme_height'] = labelme_data['imageHeight']
114
+
115
+ shapes = labelme_data['shapes']
116
+
117
+ if ('flags' in labelme_data) and (len(labelme_data['flags']) > 0):
118
+ im['flags'] = labelme_data['flags']
119
+
120
+ annotations_this_image = []
121
+
122
+ if len(shapes) == 0:
123
+
124
+ if allow_new_categories:
125
+ category_id = _add_category('empty',category_name_to_id)
126
+ else:
127
+ assert 'empty' in category_name_to_id
128
+ category_id = category_name_to_id['empty']
129
+
130
+ ann = {}
131
+ ann['id'] = str(uuid.uuid1())
132
+ ann['image_id'] = im['id']
133
+ ann['category_id'] = category_id
134
+ ann['sequence_level_annotation'] = False
135
+ annotations_this_image.append(ann)
136
+
137
+ else:
138
+
139
+ for shape in shapes:
140
+
141
+ if shape['shape_type'] != 'rectangle':
142
+ print('Only rectangles are supported, skipping an annotation of type {} in {}'.format(
143
+ shape['shape_type'],image_fn_relative))
144
+ continue
145
+
146
+ if use_folders_as_labels:
147
+ category_name = os.path.basename(os.path.dirname(image_fn_abs))
148
+ else:
149
+ category_name = shape['label']
150
+
151
+ if allow_new_categories:
152
+ category_id = _add_category(category_name,category_name_to_id)
153
+ else:
154
+ assert category_name in category_name_to_id
155
+ category_id = category_name_to_id[category_name]
156
+
157
+ points = shape['points']
158
+ if len(points) != 2:
159
+ print('Warning: illegal rectangle with {} points for {}'.format(
160
+ len(points),image_fn_relative))
161
+ continue
162
+
163
+ p0 = points[0]
164
+ p1 = points[1]
165
+ x0 = min(p0[0],p1[0])
166
+ x1 = max(p0[0],p1[0])
167
+ y0 = min(p0[1],p1[1])
168
+ y1 = max(p0[1],p1[1])
169
+
170
+ bbox = [x0,y0,abs(x1-x0),abs(y1-y0)]
171
+ ann = {}
172
+ ann['id'] = str(uuid.uuid1())
173
+ ann['image_id'] = im['id']
174
+ ann['category_id'] = category_id
175
+ ann['sequence_level_annotation'] = False
176
+ ann['bbox'] = bbox
177
+ annotations_this_image.append(ann)
178
+
179
+ # ...for each shape
180
+
181
+ result['im'] = im
182
+ result['annotations_this_image'] = annotations_this_image
183
+
184
+ return result
185
+
186
+ # ...def _process_labelme_file(...)
187
+
188
+
189
+ #%% Main function
190
+
191
+ def labelme_to_coco(input_folder,
192
+ output_file=None,
193
+ category_id_to_category_name=None,
194
+ empty_category_name='empty',
195
+ empty_category_id=None,
196
+ info_struct=None,
197
+ relative_paths_to_include=None,
198
+ relative_paths_to_exclude=None,
199
+ use_folders_as_labels=False,
200
+ recursive=True,
201
+ no_json_handling='skip',
202
+ validate_image_sizes=True,
203
+ max_workers=1,
204
+ use_threads=True):
205
+ """
206
+ Finds all images in [input_folder] that have corresponding .json files, and converts
207
+ to a COCO .json file.
208
+
209
+ Currently only supports bounding box annotations and image-level flags (i.e., does not
210
+ support point or general polygon annotations).
211
+
212
+ Labelme's image-level flags don't quite fit the COCO annotations format, so they are attached
213
+ to image objects, rather than annotation objects.
214
+
215
+ If output_file is None, just returns the resulting dict, does not write to file.
216
+
217
+ if use_folders_as_labels is False (default), the output labels come from the labelme
218
+ .json files. If use_folders_as_labels is True, the lowest-level folder name containing
219
+ each .json file will determine the output label. E.g., if use_folders_as_labels is True,
220
+ and the folder contains:
221
+
222
+ images/train/lion/image0001.json
223
+
224
+ ...all boxes in image0001.json will be given the label "lion", regardless of the labels in the
225
+ file. Empty images in the "lion" folder will still be given the label "empty" (or
226
+ [empty_category_name]).
227
+
228
+ Args:
229
+ input_folder (str): input folder to search for images and Labelme .json files
230
+ output_file (str, optional): output file to which we should write COCO-formatted data; if None
231
+ this function just returns the COCO-formatted dict
232
+ category_id_to_category_name (dict, optional): dict mapping category IDs to category names;
233
+ really used to map Labelme category names to COCO category IDs. IDs will be auto-generated
234
+ if this is None.
235
+ empty_category_name (str, optional): if images are present without boxes, the category name
236
+ we should use for whole-image (and not-very-COCO-like) empty categories.
237
+ empty_category_id (int, optional): category ID to use for the not-very-COCO-like "empty" category;
238
+ also see the no_json_handling parameter.
239
+ info_struct (dict, optional): dict to stash in the "info" field of the resulting COCO dict
240
+ relative_paths_to_include (list, optional): allowlist of relative paths to include in the COCO
241
+ dict; there's no reason to specify this along with relative_paths_to_exclude.
242
+ relative_paths_to_exclude (list, optional): blocklist of relative paths to exclude from the COCO
243
+ dict; there's no reason to specify this along with relative_paths_to_include.
244
+ use_folders_as_labels (bool, optional): if this is True, class names will be pulled from folder names,
245
+ useful if you have images like a/b/cat/image001.jpg, a/b/dog/image002.jpg, etc.
246
+ recursive (bool, optional): whether to recurse into [input_folder]
247
+ no_json_handling (str, optional): how to deal with image files that have no corresponding .json files,
248
+ can be:
249
+
250
+ - 'skip': ignore image files with no corresponding .json files
251
+ - 'empty': treat image files with no corresponding .json files as empty
252
+ - 'error': throw an error when an image file has no corresponding .json file
253
+ validate_image_sizes (bool, optional): whether to load images to verify that the sizes specified
254
+ in the labelme files are correct
255
+ max_workers (int, optional): number of workers to use for parallelization, set to <=1 to disable
256
+ parallelization
257
+ use_threads (bool, optional): whether to use threads (True) or processes (False) for parallelization,
258
+ not relevant if max_workers <= 1
259
+
260
+ Returns:
261
+ dict: a COCO-formatted dictionary, identical to what's written to [output_file] if [output_file] is not None.
262
+ """
263
+
264
+ if max_workers > 1:
265
+ assert category_id_to_category_name is not None, \
266
+ 'When parallelizing labelme --> COCO conversion, you must supply a category mapping'
267
+
268
+ if category_id_to_category_name is None:
269
+ category_name_to_id = {}
270
+ else:
271
+ category_name_to_id = {v: k for k, v in category_id_to_category_name.items()}
272
+ for category_name in category_name_to_id:
273
+ try:
274
+ category_name_to_id[category_name] = int(category_name_to_id[category_name])
275
+ except ValueError:
276
+ raise ValueError('Category IDs must be ints or string-formatted ints')
277
+
278
+ # If the user supplied an explicit empty category ID, and the empty category
279
+ # name is already in category_name_to_id, make sure they match.
280
+ if empty_category_id is not None:
281
+ if empty_category_name in category_name_to_id:
282
+ assert category_name_to_id[empty_category_name] == empty_category_id, \
283
+ 'Ambiguous empty category specification'
284
+ if empty_category_id in category_id_to_category_name:
285
+ assert category_id_to_category_name[empty_category_id] == empty_category_name, \
286
+ 'Ambiguous empty category specification'
287
+ else:
288
+ if empty_category_name in category_name_to_id:
289
+ empty_category_id = category_name_to_id[empty_category_name]
290
+
291
+ del category_id_to_category_name
292
+
293
+ # Enumerate images
294
+ print('Enumerating images in {}'.format(input_folder))
295
+ image_filenames_relative = path_utils.find_images(input_folder,
296
+ recursive=recursive,
297
+ return_relative_paths=True,
298
+ convert_slashes=True)
299
+
300
+ # Remove any images we're supposed to skip
301
+ if (relative_paths_to_include is not None) or (relative_paths_to_exclude is not None):
302
+ image_filenames_relative_to_process = []
303
+ for image_fn_relative in image_filenames_relative:
304
+ if relative_paths_to_include is not None and image_fn_relative not in relative_paths_to_include:
305
+ continue
306
+ if relative_paths_to_exclude is not None and image_fn_relative in relative_paths_to_exclude:
307
+ continue
308
+ image_filenames_relative_to_process.append(image_fn_relative)
309
+ print('Processing {} of {} images'.format(
310
+ len(image_filenames_relative_to_process),
311
+ len(image_filenames_relative)))
312
+ image_filenames_relative = image_filenames_relative_to_process
313
+
314
+ # If the user supplied a category ID to use for empty images...
315
+ if empty_category_id is not None:
316
+ try:
317
+ empty_category_id = int(empty_category_id)
318
+ except ValueError:
319
+ raise ValueError('Category IDs must be ints or string-formatted ints')
320
+
321
+ if empty_category_id is None:
322
+ empty_category_id = _add_category(empty_category_name,category_name_to_id)
323
+
324
+ if max_workers <= 1:
325
+
326
+ image_results = []
327
+ for image_fn_relative in tqdm(image_filenames_relative):
328
+
329
+ result = _process_labelme_file(image_fn_relative,input_folder,use_folders_as_labels,
330
+ no_json_handling,validate_image_sizes,
331
+ category_name_to_id,allow_new_categories=True)
332
+ image_results.append(result)
333
+
334
+ else:
335
+
336
+ n_workers = min(max_workers,len(image_filenames_relative))
337
+ assert category_name_to_id is not None
338
+
339
+ pool = None
340
+ try:
341
+ if use_threads:
342
+ pool = ThreadPool(n_workers)
343
+ else:
344
+ pool = Pool(n_workers)
345
+
346
+ image_results = list(tqdm(pool.imap(
347
+ partial(_process_labelme_file,
348
+ input_folder=input_folder,
349
+ use_folders_as_labels=use_folders_as_labels,
350
+ no_json_handling=no_json_handling,
351
+ validate_image_sizes=validate_image_sizes,
352
+ category_name_to_id=category_name_to_id,
353
+ allow_new_categories=False
354
+ ),image_filenames_relative), total=len(image_filenames_relative)))
355
+ finally:
356
+ if pool is not None:
357
+ pool.close()
358
+ pool.join()
359
+ print('Pool closed and joined for labelme file processing')
360
+
361
+ images = []
362
+ annotations = []
363
+
364
+ # Flatten the lists of images and annotations
365
+ for result in image_results:
366
+ im = result['im']
367
+ annotations_this_image = result['annotations_this_image']
368
+
369
+ if im is None:
370
+ assert annotations_this_image is None
371
+ else:
372
+ images.append(im)
373
+ annotations.extend(annotations_this_image)
374
+
375
+ output_dict = {}
376
+ output_dict['images'] = images
377
+ output_dict['annotations'] = annotations
378
+
379
+ if info_struct is None:
380
+ info_struct = {}
381
+ if 'description' not in info_struct:
382
+ info_struct['description'] = \
383
+ 'Converted to COCO from labelme annotations in folder {}'.format(input_folder)
384
+ if 'version' not in info_struct:
385
+ info_struct['version'] = 1.0
386
+
387
+ output_dict['info'] = info_struct
388
+ categories = []
389
+ for category_name in category_name_to_id:
390
+ categories.append({'name':category_name,'id':category_name_to_id[category_name]})
391
+ output_dict['categories'] = categories
392
+
393
+ if output_file is not None:
394
+ with open(output_file,'w') as f:
395
+ json.dump(output_dict,f,indent=1)
396
+
397
+ return output_dict
398
+
399
+ # ...def labelme_to_coco()
400
+
401
+
402
+ def find_empty_labelme_files(input_folder,recursive=True):
403
+ """
404
+ Returns a list of all image files in in [input_folder] associated with .json files that have
405
+ no boxes in them. Also returns a list of images with no associated .json files. Specifically,
406
+ returns a dict:
407
+
408
+ .. code-block: none
409
+
410
+ {
411
+ 'images_with_empty_json_files':[list],
412
+ 'images_with_no_json_files':[list],
413
+ 'images_with_non_empty_json_files':[list]
414
+ }
415
+
416
+ Args:
417
+ input_folder (str): the folder to search for empty (i.e., box-less) Labelme .json files
418
+ recursive (bool, optional): whether to recurse into [input_folder]
419
+
420
+ Returns:
421
+ dict: a dict with fields:
422
+ - images_with_empty_json_files: a list of all image files in [input_folder] associated with
423
+ .json files that have no boxes in them
424
+ - images_with_no_json_files: a list of images in [input_folder] with no associated .json files
425
+ - images_with_non_empty_json_files: a list of images in [input_folder] associated with .json
426
+ files that have at least one box
427
+ """
428
+
429
+ image_filenames_relative = path_utils.find_images(input_folder,
430
+ recursive=recursive,
431
+ return_relative_paths=True)
432
+
433
+ images_with_empty_json_files = []
434
+ images_with_no_json_files = []
435
+ images_with_non_empty_json_files = []
436
+
437
+ # fn_relative = image_filenames_relative[0]
438
+ for fn_relative in image_filenames_relative:
439
+
440
+ image_fn_abs = os.path.join(input_folder,fn_relative)
441
+ json_fn_abs = os.path.splitext(image_fn_abs)[0] + '.json'
442
+
443
+ if not os.path.isfile(json_fn_abs):
444
+ images_with_no_json_files.append(fn_relative)
445
+ continue
446
+
447
+ else:
448
+ # Read the .json file
449
+ with open(json_fn_abs,'r') as f:
450
+ labelme_data = json.load(f)
451
+ shapes = labelme_data['shapes']
452
+ if len(shapes) == 0:
453
+ images_with_empty_json_files.append(fn_relative)
454
+ else:
455
+ images_with_non_empty_json_files.append(fn_relative)
456
+
457
+ # ...for every image
458
+
459
+ return {'images_with_empty_json_files':images_with_empty_json_files,
460
+ 'images_with_no_json_files':images_with_no_json_files,
461
+ 'images_with_non_empty_json_files':images_with_non_empty_json_files}
462
+
463
+ # ...def find_empty_labelme_files(...)
464
+
465
+
466
+ #%% Interactive driver
467
+
468
+ if False:
469
+
470
+ pass
471
+
472
+ #%% Options
473
+
474
+ empty_category_name = 'empty'
475
+ empty_category_id = None
476
+ category_id_to_category_name = None
477
+ info_struct = None
478
+
479
+ input_folder = os.path.expanduser('~/data/md-test')
480
+ output_file = os.path.expanduser('~/data/md-test-labelme-to-coco.json')
481
+
482
+
483
+ #%% Programmatic execution
484
+
485
+ output_dict = labelme_to_coco(input_folder,output_file,
486
+ category_id_to_category_name=category_id_to_category_name,
487
+ empty_category_name=empty_category_name,
488
+ empty_category_id=empty_category_id,
489
+ info_struct=None,
490
+ use_folders_as_labels=False,
491
+ validate_image_sizes=False,
492
+ no_json_handling='empty')
493
+
494
+
495
+ #%% Validate
496
+
497
+ from megadetector.data_management.databases import integrity_check_json_db
498
+
499
+ options = integrity_check_json_db.IntegrityCheckOptions()
500
+
501
+ options.baseDir = input_folder
502
+ options.bCheckImageSizes = True
503
+ options.bCheckImageExistence = True
504
+ options.bFindUnusedImages = True
505
+ options.bRequireLocation = False
506
+
507
+ sorted_categories, _, error_info = integrity_check_json_db.integrity_check_json_db(output_file,options)
508
+
509
+
510
+ #%% Preview
511
+
512
+ from megadetector.visualization import visualize_db
513
+ options = visualize_db.DbVizOptions()
514
+ options.parallelize_rendering = True
515
+ options.viz_size = (900, -1)
516
+ options.num_to_visualize = 5000
517
+
518
+ html_file,_ = visualize_db.visualize_db(output_file,os.path.expanduser('~/tmp/labelme_to_coco_preview'),
519
+ input_folder,options)
520
+
521
+
522
+ from megadetector.utils import path_utils # noqa
523
+ path_utils.open_file(html_file)
524
+
525
+
526
+ #%% Prepare command line
527
+
528
+ s = 'python labelme_to_coco.py {} {}'.format(input_folder,output_file)
529
+ print(s)
530
+ import clipboard; clipboard.copy(s)
531
+
532
+
533
+ #%% Command-line driver
534
+
535
+ def main(): # noqa
536
+
537
+ parser = argparse.ArgumentParser(
538
+ description='Convert labelme-formatted data to COCO')
539
+
540
+ parser.add_argument(
541
+ 'input_folder',
542
+ type=str,
543
+ help='Path to images and .json annotation files')
544
+
545
+ parser.add_argument(
546
+ 'output_file',
547
+ type=str,
548
+ help='Output filename (.json)')
549
+
550
+ if len(sys.argv[1:]) == 0:
551
+ parser.print_help()
552
+ parser.exit()
553
+
554
+ args = parser.parse_args()
555
+
556
+ labelme_to_coco(args.input_folder,args.output_file)
557
+
558
+ if __name__ == '__main__':
559
+ main()