megadetector 5.0.27__py3-none-any.whl → 5.0.29__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 (176) hide show
  1. megadetector/api/batch_processing/api_core/batch_service/score.py +4 -5
  2. megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +1 -1
  3. megadetector/api/batch_processing/api_support/summarize_daily_activity.py +1 -1
  4. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +2 -2
  5. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +1 -1
  6. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +1 -1
  7. megadetector/api/synchronous/api_core/tests/load_test.py +2 -3
  8. megadetector/classification/aggregate_classifier_probs.py +3 -3
  9. megadetector/classification/analyze_failed_images.py +5 -5
  10. megadetector/classification/cache_batchapi_outputs.py +5 -5
  11. megadetector/classification/create_classification_dataset.py +11 -12
  12. megadetector/classification/crop_detections.py +10 -10
  13. megadetector/classification/csv_to_json.py +8 -8
  14. megadetector/classification/detect_and_crop.py +13 -15
  15. megadetector/classification/evaluate_model.py +7 -7
  16. megadetector/classification/identify_mislabeled_candidates.py +6 -6
  17. megadetector/classification/json_to_azcopy_list.py +1 -1
  18. megadetector/classification/json_validator.py +29 -32
  19. megadetector/classification/map_classification_categories.py +9 -9
  20. megadetector/classification/merge_classification_detection_output.py +12 -9
  21. megadetector/classification/prepare_classification_script.py +19 -19
  22. megadetector/classification/prepare_classification_script_mc.py +23 -23
  23. megadetector/classification/run_classifier.py +4 -4
  24. megadetector/classification/save_mislabeled.py +6 -6
  25. megadetector/classification/train_classifier.py +1 -1
  26. megadetector/classification/train_classifier_tf.py +9 -9
  27. megadetector/classification/train_utils.py +10 -10
  28. megadetector/data_management/annotations/annotation_constants.py +1 -1
  29. megadetector/data_management/camtrap_dp_to_coco.py +45 -45
  30. megadetector/data_management/cct_json_utils.py +101 -101
  31. megadetector/data_management/cct_to_md.py +49 -49
  32. megadetector/data_management/cct_to_wi.py +33 -33
  33. megadetector/data_management/coco_to_labelme.py +75 -75
  34. megadetector/data_management/coco_to_yolo.py +189 -189
  35. megadetector/data_management/databases/add_width_and_height_to_db.py +3 -2
  36. megadetector/data_management/databases/combine_coco_camera_traps_files.py +38 -38
  37. megadetector/data_management/databases/integrity_check_json_db.py +202 -188
  38. megadetector/data_management/databases/subset_json_db.py +33 -33
  39. megadetector/data_management/generate_crops_from_cct.py +38 -38
  40. megadetector/data_management/get_image_sizes.py +54 -49
  41. megadetector/data_management/labelme_to_coco.py +130 -124
  42. megadetector/data_management/labelme_to_yolo.py +78 -72
  43. megadetector/data_management/lila/create_lila_blank_set.py +81 -83
  44. megadetector/data_management/lila/create_lila_test_set.py +32 -31
  45. megadetector/data_management/lila/create_links_to_md_results_files.py +18 -18
  46. megadetector/data_management/lila/download_lila_subset.py +21 -24
  47. megadetector/data_management/lila/generate_lila_per_image_labels.py +91 -91
  48. megadetector/data_management/lila/get_lila_annotation_counts.py +30 -30
  49. megadetector/data_management/lila/get_lila_image_counts.py +22 -22
  50. megadetector/data_management/lila/lila_common.py +70 -70
  51. megadetector/data_management/lila/test_lila_metadata_urls.py +13 -14
  52. megadetector/data_management/mewc_to_md.py +339 -340
  53. megadetector/data_management/ocr_tools.py +258 -252
  54. megadetector/data_management/read_exif.py +232 -223
  55. megadetector/data_management/remap_coco_categories.py +26 -26
  56. megadetector/data_management/remove_exif.py +31 -20
  57. megadetector/data_management/rename_images.py +187 -187
  58. megadetector/data_management/resize_coco_dataset.py +41 -41
  59. megadetector/data_management/speciesnet_to_md.py +41 -41
  60. megadetector/data_management/wi_download_csv_to_coco.py +55 -55
  61. megadetector/data_management/yolo_output_to_md_output.py +117 -120
  62. megadetector/data_management/yolo_to_coco.py +195 -188
  63. megadetector/detection/change_detection.py +831 -0
  64. megadetector/detection/process_video.py +341 -338
  65. megadetector/detection/pytorch_detector.py +308 -266
  66. megadetector/detection/run_detector.py +186 -166
  67. megadetector/detection/run_detector_batch.py +366 -364
  68. megadetector/detection/run_inference_with_yolov5_val.py +328 -325
  69. megadetector/detection/run_tiled_inference.py +312 -253
  70. megadetector/detection/tf_detector.py +24 -24
  71. megadetector/detection/video_utils.py +291 -283
  72. megadetector/postprocessing/add_max_conf.py +15 -11
  73. megadetector/postprocessing/categorize_detections_by_size.py +44 -44
  74. megadetector/postprocessing/classification_postprocessing.py +808 -311
  75. megadetector/postprocessing/combine_batch_outputs.py +20 -21
  76. megadetector/postprocessing/compare_batch_results.py +528 -517
  77. megadetector/postprocessing/convert_output_format.py +97 -97
  78. megadetector/postprocessing/create_crop_folder.py +220 -147
  79. megadetector/postprocessing/detector_calibration.py +173 -168
  80. megadetector/postprocessing/generate_csv_report.py +508 -0
  81. megadetector/postprocessing/load_api_results.py +25 -22
  82. megadetector/postprocessing/md_to_coco.py +129 -98
  83. megadetector/postprocessing/md_to_labelme.py +89 -83
  84. megadetector/postprocessing/md_to_wi.py +40 -40
  85. megadetector/postprocessing/merge_detections.py +87 -114
  86. megadetector/postprocessing/postprocess_batch_results.py +319 -302
  87. megadetector/postprocessing/remap_detection_categories.py +36 -36
  88. megadetector/postprocessing/render_detection_confusion_matrix.py +205 -199
  89. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +57 -57
  90. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +27 -28
  91. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +702 -677
  92. megadetector/postprocessing/separate_detections_into_folders.py +226 -211
  93. megadetector/postprocessing/subset_json_detector_output.py +265 -262
  94. megadetector/postprocessing/top_folders_to_bottom.py +45 -45
  95. megadetector/postprocessing/validate_batch_results.py +70 -70
  96. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +52 -52
  97. megadetector/taxonomy_mapping/map_new_lila_datasets.py +15 -15
  98. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +14 -14
  99. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +66 -69
  100. megadetector/taxonomy_mapping/retrieve_sample_image.py +16 -16
  101. megadetector/taxonomy_mapping/simple_image_download.py +8 -8
  102. megadetector/taxonomy_mapping/species_lookup.py +33 -33
  103. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +14 -14
  104. megadetector/taxonomy_mapping/taxonomy_graph.py +11 -11
  105. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +13 -13
  106. megadetector/utils/azure_utils.py +22 -22
  107. megadetector/utils/ct_utils.py +1019 -200
  108. megadetector/utils/directory_listing.py +21 -77
  109. megadetector/utils/gpu_test.py +22 -22
  110. megadetector/utils/md_tests.py +541 -518
  111. megadetector/utils/path_utils.py +1511 -406
  112. megadetector/utils/process_utils.py +41 -41
  113. megadetector/utils/sas_blob_utils.py +53 -49
  114. megadetector/utils/split_locations_into_train_val.py +73 -60
  115. megadetector/utils/string_utils.py +147 -26
  116. megadetector/utils/url_utils.py +463 -173
  117. megadetector/utils/wi_utils.py +2629 -2868
  118. megadetector/utils/write_html_image_list.py +137 -137
  119. megadetector/visualization/plot_utils.py +21 -21
  120. megadetector/visualization/render_images_with_thumbnails.py +37 -73
  121. megadetector/visualization/visualization_utils.py +424 -404
  122. megadetector/visualization/visualize_db.py +197 -190
  123. megadetector/visualization/visualize_detector_output.py +126 -98
  124. {megadetector-5.0.27.dist-info → megadetector-5.0.29.dist-info}/METADATA +6 -3
  125. megadetector-5.0.29.dist-info/RECORD +163 -0
  126. {megadetector-5.0.27.dist-info → megadetector-5.0.29.dist-info}/WHEEL +1 -1
  127. megadetector/data_management/importers/add_nacti_sizes.py +0 -52
  128. megadetector/data_management/importers/add_timestamps_to_icct.py +0 -79
  129. megadetector/data_management/importers/animl_results_to_md_results.py +0 -158
  130. megadetector/data_management/importers/auckland_doc_test_to_json.py +0 -373
  131. megadetector/data_management/importers/auckland_doc_to_json.py +0 -201
  132. megadetector/data_management/importers/awc_to_json.py +0 -191
  133. megadetector/data_management/importers/bellevue_to_json.py +0 -272
  134. megadetector/data_management/importers/cacophony-thermal-importer.py +0 -793
  135. megadetector/data_management/importers/carrizo_shrubfree_2018.py +0 -269
  136. megadetector/data_management/importers/carrizo_trail_cam_2017.py +0 -289
  137. megadetector/data_management/importers/cct_field_adjustments.py +0 -58
  138. megadetector/data_management/importers/channel_islands_to_cct.py +0 -913
  139. megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +0 -180
  140. megadetector/data_management/importers/eMammal/eMammal_helpers.py +0 -249
  141. megadetector/data_management/importers/eMammal/make_eMammal_json.py +0 -223
  142. megadetector/data_management/importers/ena24_to_json.py +0 -276
  143. megadetector/data_management/importers/filenames_to_json.py +0 -386
  144. megadetector/data_management/importers/helena_to_cct.py +0 -283
  145. megadetector/data_management/importers/idaho-camera-traps.py +0 -1407
  146. megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +0 -294
  147. megadetector/data_management/importers/import_desert_lion_conservation_camera_traps.py +0 -387
  148. megadetector/data_management/importers/jb_csv_to_json.py +0 -150
  149. megadetector/data_management/importers/mcgill_to_json.py +0 -250
  150. megadetector/data_management/importers/missouri_to_json.py +0 -490
  151. megadetector/data_management/importers/nacti_fieldname_adjustments.py +0 -79
  152. megadetector/data_management/importers/noaa_seals_2019.py +0 -181
  153. megadetector/data_management/importers/osu-small-animals-to-json.py +0 -364
  154. megadetector/data_management/importers/pc_to_json.py +0 -365
  155. megadetector/data_management/importers/plot_wni_giraffes.py +0 -123
  156. megadetector/data_management/importers/prepare_zsl_imerit.py +0 -131
  157. megadetector/data_management/importers/raic_csv_to_md_results.py +0 -416
  158. megadetector/data_management/importers/rspb_to_json.py +0 -356
  159. megadetector/data_management/importers/save_the_elephants_survey_A.py +0 -320
  160. megadetector/data_management/importers/save_the_elephants_survey_B.py +0 -329
  161. megadetector/data_management/importers/snapshot_safari_importer.py +0 -758
  162. megadetector/data_management/importers/snapshot_serengeti_lila.py +0 -1067
  163. megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +0 -150
  164. megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +0 -153
  165. megadetector/data_management/importers/sulross_get_exif.py +0 -65
  166. megadetector/data_management/importers/timelapse_csv_set_to_json.py +0 -490
  167. megadetector/data_management/importers/ubc_to_json.py +0 -399
  168. megadetector/data_management/importers/umn_to_json.py +0 -507
  169. megadetector/data_management/importers/wellington_to_json.py +0 -263
  170. megadetector/data_management/importers/wi_to_json.py +0 -442
  171. megadetector/data_management/importers/zamba_results_to_md_results.py +0 -180
  172. megadetector/data_management/lila/add_locations_to_island_camera_traps.py +0 -101
  173. megadetector/data_management/lila/add_locations_to_nacti.py +0 -151
  174. megadetector-5.0.27.dist-info/RECORD +0 -208
  175. {megadetector-5.0.27.dist-info → megadetector-5.0.29.dist-info}/licenses/LICENSE +0 -0
  176. {megadetector-5.0.27.dist-info → megadetector-5.0.29.dist-info}/top_level.txt +0 -0
@@ -1,490 +0,0 @@
1
- """
2
-
3
- missouri_to_json.py
4
-
5
- Create .json files from the original source files for the Missouri Camera Traps
6
- data set. Metadata was provided here in two formats:
7
-
8
- 1) In one subset of the data, folder names indicated species names. In Set 1,
9
- there are no empty sequences. Set 1 has a metadata file to indicate image-level
10
- bounding boxes.
11
-
12
- 2) A subset of the data (overlapping with (1)) was annotated with bounding
13
- boxes, specified in a whitespace-delimited text file. In set 2, there are
14
- some sequences omitted from the metadata file, which implied emptiness.
15
-
16
- In the end, set 2 labels were not reliable enough to publish, so LILA includes only set 1.
17
-
18
- """
19
-
20
- #%% Constants and imports
21
-
22
- import json
23
- import os
24
- import uuid
25
- import time
26
- import humanfriendly
27
- import warnings
28
- import ntpath
29
- import datetime
30
-
31
- from PIL import Image
32
-
33
- # ignoring all "PIL cannot read EXIF metainfo for the images" warnings
34
- warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning)
35
- # Metadata Warning, tag 256 had too many entries: 42, expected 1
36
- warnings.filterwarnings("ignore", "Metadata warning", UserWarning)
37
-
38
- baseDir = os.path.expanduser('~/tmp/mct')
39
- imageDir = os.path.join(baseDir,'images')
40
-
41
- outputJsonFilenameSet1 = os.path.join(baseDir,'missouri_camera_traps_set1.json')
42
- outputEncoding = 'utf-8'
43
- fileListJsonFilename = os.path.join(baseDir,'images.json')
44
-
45
- # This will be a list of filenames that need re-annotation due to redundant boxes
46
- set1RedundantBoxListFilename = os.path.join(baseDir,'mct_images_with_redundant_boxes.txt')
47
-
48
- set1BaseDir = os.path.join(imageDir,'Set1')
49
-
50
- metadataFilenameSet1 = os.path.join(set1BaseDir,'labels.txt')
51
-
52
- assert(os.path.isdir(baseDir))
53
- assert(os.path.isfile(metadataFilenameSet1))
54
-
55
- info = {}
56
- info['year'] = 2019
57
- info['version'] = '1.21'
58
- info['description'] = 'Missouri Camera Traps (set 1)'
59
- info['contributor'] = ''
60
- info['date_created'] = str(datetime.date.today())
61
- infoSet1 = info
62
-
63
- maxFiles = -1
64
- emptyCategoryId = 0
65
- emptyCategoryName = 'empty'
66
-
67
-
68
- #%% Enumerate files, read image sizes
69
-
70
- # Takes a few minutes, since we're reading image sizes.
71
-
72
- # Each element will be a list of relative path/full path/width/height
73
- fileInfo = []
74
- nonImages = []
75
- nFiles = 0
76
-
77
- relPathToIm = {}
78
- imageIdToImage = {}
79
-
80
- set1ImageIDs = []
81
-
82
- sequenceIDtoCount = {}
83
-
84
- print('Enumerating files from {} to {}'.format(imageDir,fileListJsonFilename))
85
-
86
- startTime = time.time()
87
-
88
- for root, subdirs, files in os.walk(imageDir):
89
-
90
- if root == imageDir:
91
- continue
92
-
93
- bn = ntpath.basename(root)
94
-
95
- # Only process leaf nodes corresponding to sequences, which look like:
96
- #
97
- # Set1/1.02-Agouti/SEQ75583
98
- #
99
- if ('Set1' in root and 'SEQ' in bn):
100
- sequenceID = bn
101
- assert sequenceID not in sequenceIDtoCount
102
- sequenceIDtoCount[sequenceID] = 0
103
- else:
104
- print('Skipping folder {}:{}'.format(root,bn))
105
- continue
106
- # assert len(files) <= 2
107
-
108
- for fname in files:
109
-
110
- nFiles = nFiles + 1
111
- if maxFiles >= 0 and nFiles > maxFiles:
112
- print('Warning: early break at {} files'.format(maxFiles))
113
- break
114
-
115
- fullPath = os.path.join(root,fname)
116
- relativePath = os.path.relpath(fullPath,imageDir)
117
-
118
- if maxFiles >= 0:
119
- print(relativePath)
120
-
121
- h = -1
122
- w = -1
123
-
124
- # Read the image
125
- try:
126
-
127
- im = Image.open(fullPath)
128
- h = im.height
129
- w = im.width
130
-
131
- except:
132
-
133
- # Not an image...
134
- continue
135
-
136
- # Store file info
137
- im = {}
138
- im['id'] = str(uuid.uuid1())
139
- im['file_name'] = relativePath
140
- im['height'] = h
141
- im['width'] = w
142
- im['location'] = 'missouri_camera_traps'
143
-
144
- im['seq_id'] = sequenceID
145
- im['seq_num_frames'] = -1
146
-
147
- frame_number = sequenceIDtoCount[sequenceID]
148
- im['frame_num'] = frame_number
149
- sequenceIDtoCount[sequenceID] = sequenceIDtoCount[sequenceID] + 1
150
-
151
- imageIdToImage[im['id']] = im
152
- relPathToIm[relativePath] = im
153
-
154
- if 'Set1' in relativePath:
155
- set1ImageIDs.append(im['id'])
156
- else:
157
- raise Exception('Oops, can''t assign this image to a set')
158
-
159
- # ...if we didn't hit the max file limit, keep going
160
-
161
- else:
162
-
163
- continue
164
-
165
- break
166
-
167
- # ...for each file
168
-
169
- elapsed = time.time() - startTime
170
- print('Finished file enumeration in {}'.format(
171
- humanfriendly.format_timespan(elapsed)))
172
-
173
-
174
- #%% Add sequence lengths
175
-
176
- for imageID in imageIdToImage:
177
-
178
- im = imageIdToImage[imageID]
179
- sequenceID = im['seq_id']
180
- seq_num_frames = sequenceIDtoCount[sequenceID]
181
- assert(im['seq_num_frames'] == -1)
182
- im['seq_num_frames'] = seq_num_frames
183
-
184
-
185
- #%% Load the metadata (.txt) file
186
-
187
- with open(metadataFilenameSet1) as f:
188
- metadataSet1Lines = f.readlines()
189
-
190
- metadataSet1Lines = [x.strip() for x in metadataSet1Lines]
191
-
192
-
193
- #%% Map relative paths to metadata
194
-
195
- # List of lists, length varies according to number of bounding boxes
196
- #
197
- # Preserves original ordering
198
- missingFilesSet1 = []
199
- correctedFiles = []
200
-
201
- relPathToMetadataSet1 = {}
202
-
203
- # iLine = 0; line = metadataSet1Lines[0]
204
- for iLine,line in enumerate(metadataSet1Lines):
205
-
206
- tokens = line.split()
207
- nTokens = len(tokens)
208
-
209
- # Lines should be filename, number of bounding boxes, boxes (four values per box)
210
- assert ((nTokens - 2) % 4) == 0
211
- relPath = tokens[0].replace('/',os.sep).replace('\\',os.sep)
212
- relPath = os.path.join('Set1',relPath)
213
- absPath = os.path.join(imageDir,relPath)
214
-
215
- originalAbsPath = absPath
216
- originalRelPath = relPath
217
-
218
- if not os.path.isfile(absPath):
219
-
220
- absPath = originalAbsPath.replace('IMG','IMG_')
221
- relPath = originalRelPath.replace('IMG','IMG_')
222
- if os.path.isfile(absPath):
223
- correctedFiles.append([relPath,originalRelPath,absPath,originalAbsPath])
224
-
225
- if not os.path.isfile(absPath):
226
-
227
- absPath = originalAbsPath.replace('Red_Deer','Red_Brocket_Deer').replace('IMG','IMG_')
228
- relPath = originalRelPath.replace('Red_Deer','Red_Brocket_Deer').replace('IMG','IMG_')
229
- if os.path.isfile(absPath):
230
- correctedFiles.append([relPath,originalRelPath,absPath,originalAbsPath])
231
-
232
- if not os.path.isfile(absPath):
233
-
234
- missingFilesSet1.append([originalRelPath,originalAbsPath])
235
-
236
- else:
237
-
238
- relPathToMetadataSet1[relPath] = tokens
239
-
240
- # Make sure we have image info for this image
241
- assert relPath in relPathToIm
242
-
243
- print('Corrected {} paths, missing {} images of {}'.format(len(correctedFiles),
244
- len(missingFilesSet1),len(metadataSet1Lines)))
245
-
246
-
247
- #%% Print missing files from Set 1 metadata
248
-
249
- # The only missing file (and it's really just missing):
250
- #
251
- # Set1/1.58-Roe_Deer/SEQ75631/SEQ75631_IMG_0011.JPG
252
-
253
- print('Missing files in Set 1:\n')
254
- for iFile,fInfo in enumerate(missingFilesSet1):
255
- print(fInfo[0])
256
-
257
-
258
- #%% Create categories and annotations for set 1
259
-
260
- imagesSet1 = []
261
- categoriesSet1 = []
262
- annotationsSet1 = []
263
-
264
- categoryNameToId = {}
265
- idToCategory = {}
266
-
267
- # Though we have no empty sequences, we do have empty images in this set
268
- emptyCat = {}
269
- emptyCat['id'] = emptyCategoryId
270
- emptyCat['name'] = emptyCategoryName
271
- emptyCat['count'] = 0
272
- categoriesSet1.append(emptyCat)
273
-
274
- nextCategoryId = emptyCategoryId + 1
275
-
276
- nFoundMetadata = 0
277
- nTotalBoxes = 0
278
- nImageLevelEmpties = 0
279
- nSequenceLevelAnnotations = 0
280
- nRedundantBoxes = 0
281
-
282
- imageIDsWithRedundantBoxes = set()
283
-
284
- # For each image
285
- #
286
- # iImage = 0; imageID = set1ImageIDs[iImage]
287
- for iImage,imageID in enumerate(set1ImageIDs):
288
-
289
- im = imageIdToImage[imageID]
290
- imagesSet1.append(im)
291
-
292
- # E.g. Set1\\1.80-Coiban_Agouti\\SEQ83155\\SEQ83155_IMG_0010.JPG
293
- relPath = im['file_name']
294
-
295
- # Find the species name
296
- tokens = os.path.normpath(relPath).split(os.sep)
297
- speciesTag = tokens[1]
298
- tokens = speciesTag.split('-',1)
299
- assert(len(tokens) == 2)
300
- categoryName = tokens[1].lower()
301
-
302
- category = None
303
- categoryId = None
304
-
305
- if categoryName not in categoryNameToId:
306
-
307
- categoryId = nextCategoryId
308
- nextCategoryId += 1
309
- categoryNameToId[categoryName] = categoryId
310
- newCat = {}
311
- newCat['id'] = categoryNameToId[categoryName]
312
- newCat['name'] = categoryName
313
- newCat['count'] = 0
314
- categoriesSet1.append(newCat)
315
- idToCategory[categoryId] = newCat
316
- category = newCat
317
-
318
- else:
319
-
320
- categoryId = categoryNameToId[categoryName]
321
- category = idToCategory[categoryId]
322
-
323
- # This image may still be empty...
324
- # category['count'] = category['count'] + 1
325
-
326
- # If we have bounding boxes, create image-level annotations
327
- if relPath in relPathToMetadataSet1:
328
-
329
- nFoundMetadata += 1
330
-
331
- # This tuple is:
332
- #
333
- # filename (possibly no longer correct)
334
- # number of bounding boxes
335
- # [...boxes (four values per box)]
336
- imageMetadata = relPathToMetadataSet1[relPath]
337
-
338
- nBoxes = int(imageMetadata[1])
339
- im['n_boxes'] = nBoxes
340
-
341
- if nBoxes == 0:
342
-
343
- ann = {}
344
- ann['id'] = str(uuid.uuid1())
345
- ann['image_id'] = im['id']
346
- ann['category_id'] = emptyCategoryId
347
- ann['sequence_level_annotation'] = False
348
- annotationsSet1.append(ann)
349
- emptyCat['count'] = emptyCat['count'] + 1
350
- nImageLevelEmpties += 1
351
-
352
- else:
353
-
354
- # This image is non-empty
355
- category['count'] = category['count'] + 1
356
-
357
- for iBox in range(0,nBoxes):
358
-
359
- boxCoords = imageMetadata[2+(iBox*4):6+(iBox*4)]
360
- boxCoords = list(map(int, boxCoords))
361
-
362
- # Some redundant bounding boxes crept in, don't add them twice
363
- bRedundantBox = False
364
-
365
- # Check this bbox against previous bboxes
366
- #
367
- # Inefficient? Yes. In an important way? No.
368
- for iBoxComparison in range(0,iBox):
369
- assert iBox != iBoxComparison
370
- boxCoordsComparison = imageMetadata[2+(iBoxComparison*4):6+(iBoxComparison*4)]
371
- boxCoordsComparison = list(map(int, boxCoordsComparison))
372
- if boxCoordsComparison == boxCoords:
373
- # print('Warning: redundant box on image {}'.format(relPath))
374
- bRedundantBox = True
375
- nRedundantBoxes += 1
376
- break
377
-
378
- if bRedundantBox:
379
- imageIDsWithRedundantBoxes.add(im['id'])
380
- continue
381
-
382
- # Bounding box values are in absolute coordinates, with the origin
383
- # at the upper-left of the image, as [xmin1 ymin1 xmax1 ymax1].
384
- #
385
- # Convert to floats and to x/y/w/h, as per CCT standard
386
- bboxW = boxCoords[2] - boxCoords[0]
387
- bboxH = boxCoords[3] - boxCoords[1]
388
-
389
- box = [boxCoords[0], boxCoords[1], bboxW, bboxH]
390
- box = list(map(float, box))
391
-
392
- ann = {}
393
- ann['id'] = str(uuid.uuid1())
394
- ann['image_id'] = im['id']
395
- ann['category_id'] = categoryId
396
- ann['sequence_level_annotation'] = False
397
- ann['bbox'] = box
398
- annotationsSet1.append(ann)
399
- nTotalBoxes += 1
400
-
401
- # ...for each box
402
-
403
- # if we do/don't have boxes for this image
404
-
405
- # Else create a sequence-level annotation
406
- else:
407
-
408
- ann = {}
409
- ann['id'] = str(uuid.uuid1())
410
- ann['image_id'] = im['id']
411
- ann['category_id'] = categoryId
412
- ann['sequence_level_annotation'] = True
413
- annotationsSet1.append(ann)
414
- nSequenceLevelAnnotations += 1
415
-
416
- # ...for each image
417
-
418
- print('Finished processing set 1, found metadata for {} of {} images'.format(nFoundMetadata,len(set1ImageIDs)))
419
- print('Created {} annotations and {} boxes in {} categories'.format(
420
- len(annotationsSet1),nTotalBoxes,len(categoriesSet1)))
421
- print('Found {} redundant annotations'.format(nRedundantBoxes))
422
-
423
- assert len(annotationsSet1) == nSequenceLevelAnnotations + nTotalBoxes + nImageLevelEmpties
424
- assert len(set1ImageIDs) == nSequenceLevelAnnotations + nFoundMetadata
425
-
426
- print('Found {} images with redundant boxes'.format(len(imageIDsWithRedundantBoxes)))
427
-
428
-
429
- #%% Write out the list of images with redundant boxes
430
-
431
- imageFileNamesWithRedundantBoxes = []
432
- for image_id in imageIDsWithRedundantBoxes:
433
- im = imageIdToImage[image_id]
434
- imageFileNamesWithRedundantBoxes.append(im['file_name'])
435
- imageFileNamesWithRedundantBoxes.sort()
436
-
437
- with open(set1RedundantBoxListFilename,'w') as f:
438
- for fn in imageFileNamesWithRedundantBoxes:
439
- f.write(fn + '\n')
440
-
441
-
442
- #%% The 'count' field isn't really meaningful, delete it
443
-
444
- # It's really the count of image-level annotations, not total images assigned to a class
445
- for d in categoriesSet1:
446
- del d['count']
447
-
448
-
449
- #%% Write output .json files
450
-
451
- data = {}
452
- data['info'] = infoSet1
453
- data['images'] = imagesSet1
454
- data['annotations'] = annotationsSet1
455
- data['categories'] = categoriesSet1
456
- json.dump(data, open(outputJsonFilenameSet1,'w'), indent=4)
457
- print('Finished writing json to {}'.format(outputJsonFilenameSet1))
458
-
459
-
460
- #%% Consistency-check final set 1 .json file
461
-
462
- from megadetector.data_management.databases import integrity_check_json_db
463
- options = integrity_check_json_db.IntegrityCheckOptions()
464
- options.baseDir = imageDir
465
- options.bCheckImageSizes = True
466
- options.bCheckImageExistence = True
467
- options.bFindUnusedImages = True
468
- options.bRequireLocation = False
469
- options.nThreads = 10
470
- sortedCategories,data,_ = integrity_check_json_db.integrity_check_json_db(outputJsonFilenameSet1, options)
471
- sortedCategories
472
-
473
-
474
- #%% Generate previews
475
-
476
- from megadetector.visualization import visualize_db
477
-
478
- output_dir = os.path.join(baseDir,'preview')
479
-
480
- options = visualize_db.DbVizOptions()
481
- options.num_to_visualize = 5000
482
- options.sort_by_filename = False
483
- options.classes_to_exclude = None
484
- options.trim_to_images_with_bboxes = False
485
- options.parallelize_rendering = True
486
-
487
- htmlOutputFile,_ = visualize_db.visualize_db(outputJsonFilenameSet1,output_dir,imageDir,options)
488
-
489
- from megadetector.utils.path_utils import open_file
490
- open_file(htmlOutputFile)
@@ -1,79 +0,0 @@
1
- """
2
-
3
- nacti_fieldname_adjustments.py
4
-
5
- NACTI metadata was posted with "filename" in images instead of "file_name", and
6
- used string (rather than int) category IDs (in categories, but not in annotations).
7
-
8
- This script fixes those issues and rev's the version number.
9
-
10
- """
11
-
12
- #%% Constants and environment
13
-
14
- import json
15
- import os
16
-
17
- inputJsonFile = r'/datadrive1/nacti_metadata_orig.json'
18
- outputJsonFile = r'/datadrive1/nacti_metadata.json'
19
-
20
- assert os.path.isfile(inputJsonFile)
21
-
22
-
23
- #%% Read .json file
24
-
25
- with open(inputJsonFile,'r') as f:
26
- data = json.load(f)
27
-
28
- images = data['images']
29
- annotations = data['annotations']
30
- categories = data['categories']
31
- info = data['info']
32
-
33
- print('Finished reading input .json')
34
-
35
-
36
- #%% Rev version number, update field names and types
37
-
38
- assert(info['version'] == 1.0)
39
- info['version'] = 1.1
40
- nFilenameConversions = 0
41
- nCatConversions = 0
42
- nAnnConversions = 0
43
-
44
- for image in images:
45
-
46
- assert 'path' in image and isinstance(image['path'],str)
47
- image['file_name'] = image['path']
48
- del image['path']
49
- nFilenameConversions += 1
50
- assert 'seq_no' in image
51
- del image['seq_no']
52
- assert 'width' in image and isinstance(image['width'],str)
53
- assert 'height' in image and isinstance(image['height'],str)
54
- image['width'] = int(image['width'])
55
- image['height'] = int(image['height'])
56
-
57
- for cat in categories:
58
-
59
- assert 'id' in cat and isinstance(cat['id'],str)
60
- cat['id'] = int(cat['id'])
61
- nCatConversions += 1
62
-
63
- for ann in annotations:
64
-
65
- assert 'id' in ann and isinstance(ann['id'],str)
66
- assert 'category_id' in ann and isinstance(ann['category_id'],str)
67
- ann['category_id'] = int(ann['category_id'])
68
- nAnnConversions += 1
69
-
70
- print('Finished checking data, converted {} filename fields, {} category IDs, {} annotation category IDs'.format(
71
- nFilenameConversions,nCatConversions,nAnnConversions))
72
-
73
-
74
- #%% Write json file
75
-
76
- json.dump(data, open(outputJsonFile, 'w'), indent=4)
77
-
78
- print('Finished writing output .json to {}'.format(outputJsonFile))
79
-