megadetector 5.0.28__py3-none-any.whl → 10.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

Files changed (197) hide show
  1. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +2 -2
  2. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +1 -1
  3. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +1 -1
  4. megadetector/classification/aggregate_classifier_probs.py +3 -3
  5. megadetector/classification/analyze_failed_images.py +5 -5
  6. megadetector/classification/cache_batchapi_outputs.py +5 -5
  7. megadetector/classification/create_classification_dataset.py +11 -12
  8. megadetector/classification/crop_detections.py +10 -10
  9. megadetector/classification/csv_to_json.py +8 -8
  10. megadetector/classification/detect_and_crop.py +13 -15
  11. megadetector/classification/efficientnet/model.py +8 -8
  12. megadetector/classification/efficientnet/utils.py +6 -5
  13. megadetector/classification/evaluate_model.py +7 -7
  14. megadetector/classification/identify_mislabeled_candidates.py +6 -6
  15. megadetector/classification/json_to_azcopy_list.py +1 -1
  16. megadetector/classification/json_validator.py +29 -32
  17. megadetector/classification/map_classification_categories.py +9 -9
  18. megadetector/classification/merge_classification_detection_output.py +12 -9
  19. megadetector/classification/prepare_classification_script.py +19 -19
  20. megadetector/classification/prepare_classification_script_mc.py +26 -26
  21. megadetector/classification/run_classifier.py +4 -4
  22. megadetector/classification/save_mislabeled.py +6 -6
  23. megadetector/classification/train_classifier.py +1 -1
  24. megadetector/classification/train_classifier_tf.py +9 -9
  25. megadetector/classification/train_utils.py +10 -10
  26. megadetector/data_management/annotations/annotation_constants.py +1 -2
  27. megadetector/data_management/camtrap_dp_to_coco.py +79 -46
  28. megadetector/data_management/cct_json_utils.py +103 -103
  29. megadetector/data_management/cct_to_md.py +49 -49
  30. megadetector/data_management/cct_to_wi.py +33 -33
  31. megadetector/data_management/coco_to_labelme.py +75 -75
  32. megadetector/data_management/coco_to_yolo.py +210 -193
  33. megadetector/data_management/databases/add_width_and_height_to_db.py +86 -12
  34. megadetector/data_management/databases/combine_coco_camera_traps_files.py +40 -40
  35. megadetector/data_management/databases/integrity_check_json_db.py +228 -200
  36. megadetector/data_management/databases/subset_json_db.py +33 -33
  37. megadetector/data_management/generate_crops_from_cct.py +88 -39
  38. megadetector/data_management/get_image_sizes.py +54 -49
  39. megadetector/data_management/labelme_to_coco.py +133 -125
  40. megadetector/data_management/labelme_to_yolo.py +159 -73
  41. megadetector/data_management/lila/create_lila_blank_set.py +81 -83
  42. megadetector/data_management/lila/create_lila_test_set.py +32 -31
  43. megadetector/data_management/lila/create_links_to_md_results_files.py +18 -18
  44. megadetector/data_management/lila/download_lila_subset.py +21 -24
  45. megadetector/data_management/lila/generate_lila_per_image_labels.py +365 -107
  46. megadetector/data_management/lila/get_lila_annotation_counts.py +35 -33
  47. megadetector/data_management/lila/get_lila_image_counts.py +22 -22
  48. megadetector/data_management/lila/lila_common.py +73 -70
  49. megadetector/data_management/lila/test_lila_metadata_urls.py +28 -19
  50. megadetector/data_management/mewc_to_md.py +344 -340
  51. megadetector/data_management/ocr_tools.py +262 -255
  52. megadetector/data_management/read_exif.py +249 -227
  53. megadetector/data_management/remap_coco_categories.py +90 -28
  54. megadetector/data_management/remove_exif.py +81 -21
  55. megadetector/data_management/rename_images.py +187 -187
  56. megadetector/data_management/resize_coco_dataset.py +588 -120
  57. megadetector/data_management/speciesnet_to_md.py +41 -41
  58. megadetector/data_management/wi_download_csv_to_coco.py +55 -55
  59. megadetector/data_management/yolo_output_to_md_output.py +248 -122
  60. megadetector/data_management/yolo_to_coco.py +333 -191
  61. megadetector/detection/change_detection.py +832 -0
  62. megadetector/detection/process_video.py +340 -337
  63. megadetector/detection/pytorch_detector.py +358 -278
  64. megadetector/detection/run_detector.py +399 -186
  65. megadetector/detection/run_detector_batch.py +404 -377
  66. megadetector/detection/run_inference_with_yolov5_val.py +340 -327
  67. megadetector/detection/run_tiled_inference.py +257 -249
  68. megadetector/detection/tf_detector.py +24 -24
  69. megadetector/detection/video_utils.py +332 -295
  70. megadetector/postprocessing/add_max_conf.py +19 -11
  71. megadetector/postprocessing/categorize_detections_by_size.py +45 -45
  72. megadetector/postprocessing/classification_postprocessing.py +468 -433
  73. megadetector/postprocessing/combine_batch_outputs.py +23 -23
  74. megadetector/postprocessing/compare_batch_results.py +590 -525
  75. megadetector/postprocessing/convert_output_format.py +106 -102
  76. megadetector/postprocessing/create_crop_folder.py +347 -147
  77. megadetector/postprocessing/detector_calibration.py +173 -168
  78. megadetector/postprocessing/generate_csv_report.py +508 -499
  79. megadetector/postprocessing/load_api_results.py +48 -27
  80. megadetector/postprocessing/md_to_coco.py +133 -102
  81. megadetector/postprocessing/md_to_labelme.py +107 -90
  82. megadetector/postprocessing/md_to_wi.py +40 -40
  83. megadetector/postprocessing/merge_detections.py +92 -114
  84. megadetector/postprocessing/postprocess_batch_results.py +319 -301
  85. megadetector/postprocessing/remap_detection_categories.py +91 -38
  86. megadetector/postprocessing/render_detection_confusion_matrix.py +214 -205
  87. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +57 -57
  88. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +27 -28
  89. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +704 -679
  90. megadetector/postprocessing/separate_detections_into_folders.py +226 -211
  91. megadetector/postprocessing/subset_json_detector_output.py +265 -262
  92. megadetector/postprocessing/top_folders_to_bottom.py +45 -45
  93. megadetector/postprocessing/validate_batch_results.py +70 -70
  94. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +52 -52
  95. megadetector/taxonomy_mapping/map_new_lila_datasets.py +18 -19
  96. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +54 -33
  97. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +67 -67
  98. megadetector/taxonomy_mapping/retrieve_sample_image.py +16 -16
  99. megadetector/taxonomy_mapping/simple_image_download.py +8 -8
  100. megadetector/taxonomy_mapping/species_lookup.py +156 -74
  101. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +14 -14
  102. megadetector/taxonomy_mapping/taxonomy_graph.py +10 -10
  103. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +13 -13
  104. megadetector/utils/ct_utils.py +1049 -211
  105. megadetector/utils/directory_listing.py +21 -77
  106. megadetector/utils/gpu_test.py +22 -22
  107. megadetector/utils/md_tests.py +632 -529
  108. megadetector/utils/path_utils.py +1520 -431
  109. megadetector/utils/process_utils.py +41 -41
  110. megadetector/utils/split_locations_into_train_val.py +62 -62
  111. megadetector/utils/string_utils.py +148 -27
  112. megadetector/utils/url_utils.py +489 -176
  113. megadetector/utils/wi_utils.py +2658 -2526
  114. megadetector/utils/write_html_image_list.py +137 -137
  115. megadetector/visualization/plot_utils.py +34 -30
  116. megadetector/visualization/render_images_with_thumbnails.py +39 -74
  117. megadetector/visualization/visualization_utils.py +487 -435
  118. megadetector/visualization/visualize_db.py +232 -198
  119. megadetector/visualization/visualize_detector_output.py +82 -76
  120. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/METADATA +5 -2
  121. megadetector-10.0.0.dist-info/RECORD +139 -0
  122. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/WHEEL +1 -1
  123. megadetector/api/batch_processing/api_core/__init__.py +0 -0
  124. megadetector/api/batch_processing/api_core/batch_service/__init__.py +0 -0
  125. megadetector/api/batch_processing/api_core/batch_service/score.py +0 -439
  126. megadetector/api/batch_processing/api_core/server.py +0 -294
  127. megadetector/api/batch_processing/api_core/server_api_config.py +0 -97
  128. megadetector/api/batch_processing/api_core/server_app_config.py +0 -55
  129. megadetector/api/batch_processing/api_core/server_batch_job_manager.py +0 -220
  130. megadetector/api/batch_processing/api_core/server_job_status_table.py +0 -149
  131. megadetector/api/batch_processing/api_core/server_orchestration.py +0 -360
  132. megadetector/api/batch_processing/api_core/server_utils.py +0 -88
  133. megadetector/api/batch_processing/api_core_support/__init__.py +0 -0
  134. megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +0 -46
  135. megadetector/api/batch_processing/api_support/__init__.py +0 -0
  136. megadetector/api/batch_processing/api_support/summarize_daily_activity.py +0 -152
  137. megadetector/api/batch_processing/data_preparation/__init__.py +0 -0
  138. megadetector/api/synchronous/__init__.py +0 -0
  139. megadetector/api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
  140. megadetector/api/synchronous/api_core/animal_detection_api/api_backend.py +0 -151
  141. megadetector/api/synchronous/api_core/animal_detection_api/api_frontend.py +0 -263
  142. megadetector/api/synchronous/api_core/animal_detection_api/config.py +0 -35
  143. megadetector/api/synchronous/api_core/tests/__init__.py +0 -0
  144. megadetector/api/synchronous/api_core/tests/load_test.py +0 -110
  145. megadetector/data_management/importers/add_nacti_sizes.py +0 -52
  146. megadetector/data_management/importers/add_timestamps_to_icct.py +0 -79
  147. megadetector/data_management/importers/animl_results_to_md_results.py +0 -158
  148. megadetector/data_management/importers/auckland_doc_test_to_json.py +0 -373
  149. megadetector/data_management/importers/auckland_doc_to_json.py +0 -201
  150. megadetector/data_management/importers/awc_to_json.py +0 -191
  151. megadetector/data_management/importers/bellevue_to_json.py +0 -272
  152. megadetector/data_management/importers/cacophony-thermal-importer.py +0 -793
  153. megadetector/data_management/importers/carrizo_shrubfree_2018.py +0 -269
  154. megadetector/data_management/importers/carrizo_trail_cam_2017.py +0 -289
  155. megadetector/data_management/importers/cct_field_adjustments.py +0 -58
  156. megadetector/data_management/importers/channel_islands_to_cct.py +0 -913
  157. megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +0 -180
  158. megadetector/data_management/importers/eMammal/eMammal_helpers.py +0 -249
  159. megadetector/data_management/importers/eMammal/make_eMammal_json.py +0 -223
  160. megadetector/data_management/importers/ena24_to_json.py +0 -276
  161. megadetector/data_management/importers/filenames_to_json.py +0 -386
  162. megadetector/data_management/importers/helena_to_cct.py +0 -283
  163. megadetector/data_management/importers/idaho-camera-traps.py +0 -1407
  164. megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +0 -294
  165. megadetector/data_management/importers/import_desert_lion_conservation_camera_traps.py +0 -387
  166. megadetector/data_management/importers/jb_csv_to_json.py +0 -150
  167. megadetector/data_management/importers/mcgill_to_json.py +0 -250
  168. megadetector/data_management/importers/missouri_to_json.py +0 -490
  169. megadetector/data_management/importers/nacti_fieldname_adjustments.py +0 -79
  170. megadetector/data_management/importers/noaa_seals_2019.py +0 -181
  171. megadetector/data_management/importers/osu-small-animals-to-json.py +0 -364
  172. megadetector/data_management/importers/pc_to_json.py +0 -365
  173. megadetector/data_management/importers/plot_wni_giraffes.py +0 -123
  174. megadetector/data_management/importers/prepare_zsl_imerit.py +0 -131
  175. megadetector/data_management/importers/raic_csv_to_md_results.py +0 -416
  176. megadetector/data_management/importers/rspb_to_json.py +0 -356
  177. megadetector/data_management/importers/save_the_elephants_survey_A.py +0 -320
  178. megadetector/data_management/importers/save_the_elephants_survey_B.py +0 -329
  179. megadetector/data_management/importers/snapshot_safari_importer.py +0 -758
  180. megadetector/data_management/importers/snapshot_serengeti_lila.py +0 -1067
  181. megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +0 -150
  182. megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +0 -153
  183. megadetector/data_management/importers/sulross_get_exif.py +0 -65
  184. megadetector/data_management/importers/timelapse_csv_set_to_json.py +0 -490
  185. megadetector/data_management/importers/ubc_to_json.py +0 -399
  186. megadetector/data_management/importers/umn_to_json.py +0 -507
  187. megadetector/data_management/importers/wellington_to_json.py +0 -263
  188. megadetector/data_management/importers/wi_to_json.py +0 -442
  189. megadetector/data_management/importers/zamba_results_to_md_results.py +0 -180
  190. megadetector/data_management/lila/add_locations_to_island_camera_traps.py +0 -101
  191. megadetector/data_management/lila/add_locations_to_nacti.py +0 -151
  192. megadetector/utils/azure_utils.py +0 -178
  193. megadetector/utils/sas_blob_utils.py +0 -509
  194. megadetector-5.0.28.dist-info/RECORD +0 -209
  195. /megadetector/{api/batch_processing/__init__.py → __init__.py} +0 -0
  196. {megadetector-5.0.28.dist-info → megadetector-10.0.0.dist-info}/licenses/LICENSE +0 -0
  197. {megadetector-5.0.28.dist-info → megadetector-10.0.0.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
-