megadetector 5.0.11__py3-none-any.whl → 5.0.12__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 (201) hide show
  1. megadetector/api/__init__.py +0 -0
  2. megadetector/api/batch_processing/__init__.py +0 -0
  3. megadetector/api/batch_processing/api_core/__init__.py +0 -0
  4. megadetector/api/batch_processing/api_core/batch_service/__init__.py +0 -0
  5. megadetector/api/batch_processing/api_core/batch_service/score.py +439 -0
  6. megadetector/api/batch_processing/api_core/server.py +294 -0
  7. megadetector/api/batch_processing/api_core/server_api_config.py +98 -0
  8. megadetector/api/batch_processing/api_core/server_app_config.py +55 -0
  9. megadetector/api/batch_processing/api_core/server_batch_job_manager.py +220 -0
  10. megadetector/api/batch_processing/api_core/server_job_status_table.py +152 -0
  11. megadetector/api/batch_processing/api_core/server_orchestration.py +360 -0
  12. megadetector/api/batch_processing/api_core/server_utils.py +92 -0
  13. megadetector/api/batch_processing/api_core_support/__init__.py +0 -0
  14. megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +46 -0
  15. megadetector/api/batch_processing/api_support/__init__.py +0 -0
  16. megadetector/api/batch_processing/api_support/summarize_daily_activity.py +152 -0
  17. megadetector/api/batch_processing/data_preparation/__init__.py +0 -0
  18. megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
  19. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
  20. megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
  21. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +126 -0
  22. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
  23. megadetector/api/synchronous/__init__.py +0 -0
  24. megadetector/api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
  25. megadetector/api/synchronous/api_core/animal_detection_api/api_backend.py +152 -0
  26. megadetector/api/synchronous/api_core/animal_detection_api/api_frontend.py +266 -0
  27. megadetector/api/synchronous/api_core/animal_detection_api/config.py +35 -0
  28. megadetector/api/synchronous/api_core/tests/__init__.py +0 -0
  29. megadetector/api/synchronous/api_core/tests/load_test.py +110 -0
  30. megadetector/classification/__init__.py +0 -0
  31. megadetector/classification/aggregate_classifier_probs.py +108 -0
  32. megadetector/classification/analyze_failed_images.py +227 -0
  33. megadetector/classification/cache_batchapi_outputs.py +198 -0
  34. megadetector/classification/create_classification_dataset.py +627 -0
  35. megadetector/classification/crop_detections.py +516 -0
  36. megadetector/classification/csv_to_json.py +226 -0
  37. megadetector/classification/detect_and_crop.py +855 -0
  38. megadetector/classification/efficientnet/__init__.py +9 -0
  39. megadetector/classification/efficientnet/model.py +415 -0
  40. megadetector/classification/efficientnet/utils.py +610 -0
  41. megadetector/classification/evaluate_model.py +520 -0
  42. megadetector/classification/identify_mislabeled_candidates.py +152 -0
  43. megadetector/classification/json_to_azcopy_list.py +63 -0
  44. megadetector/classification/json_validator.py +699 -0
  45. megadetector/classification/map_classification_categories.py +276 -0
  46. megadetector/classification/merge_classification_detection_output.py +506 -0
  47. megadetector/classification/prepare_classification_script.py +194 -0
  48. megadetector/classification/prepare_classification_script_mc.py +228 -0
  49. megadetector/classification/run_classifier.py +287 -0
  50. megadetector/classification/save_mislabeled.py +110 -0
  51. megadetector/classification/train_classifier.py +827 -0
  52. megadetector/classification/train_classifier_tf.py +725 -0
  53. megadetector/classification/train_utils.py +323 -0
  54. megadetector/data_management/__init__.py +0 -0
  55. megadetector/data_management/annotations/__init__.py +0 -0
  56. megadetector/data_management/annotations/annotation_constants.py +34 -0
  57. megadetector/data_management/camtrap_dp_to_coco.py +239 -0
  58. megadetector/data_management/cct_json_utils.py +395 -0
  59. megadetector/data_management/cct_to_md.py +176 -0
  60. megadetector/data_management/cct_to_wi.py +289 -0
  61. megadetector/data_management/coco_to_labelme.py +272 -0
  62. megadetector/data_management/coco_to_yolo.py +662 -0
  63. megadetector/data_management/databases/__init__.py +0 -0
  64. megadetector/data_management/databases/add_width_and_height_to_db.py +33 -0
  65. megadetector/data_management/databases/combine_coco_camera_traps_files.py +206 -0
  66. megadetector/data_management/databases/integrity_check_json_db.py +477 -0
  67. megadetector/data_management/databases/subset_json_db.py +115 -0
  68. megadetector/data_management/generate_crops_from_cct.py +149 -0
  69. megadetector/data_management/get_image_sizes.py +189 -0
  70. megadetector/data_management/importers/add_nacti_sizes.py +52 -0
  71. megadetector/data_management/importers/add_timestamps_to_icct.py +79 -0
  72. megadetector/data_management/importers/animl_results_to_md_results.py +158 -0
  73. megadetector/data_management/importers/auckland_doc_test_to_json.py +373 -0
  74. megadetector/data_management/importers/auckland_doc_to_json.py +201 -0
  75. megadetector/data_management/importers/awc_to_json.py +191 -0
  76. megadetector/data_management/importers/bellevue_to_json.py +273 -0
  77. megadetector/data_management/importers/cacophony-thermal-importer.py +796 -0
  78. megadetector/data_management/importers/carrizo_shrubfree_2018.py +269 -0
  79. megadetector/data_management/importers/carrizo_trail_cam_2017.py +289 -0
  80. megadetector/data_management/importers/cct_field_adjustments.py +58 -0
  81. megadetector/data_management/importers/channel_islands_to_cct.py +913 -0
  82. megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +180 -0
  83. megadetector/data_management/importers/eMammal/eMammal_helpers.py +249 -0
  84. megadetector/data_management/importers/eMammal/make_eMammal_json.py +223 -0
  85. megadetector/data_management/importers/ena24_to_json.py +276 -0
  86. megadetector/data_management/importers/filenames_to_json.py +386 -0
  87. megadetector/data_management/importers/helena_to_cct.py +283 -0
  88. megadetector/data_management/importers/idaho-camera-traps.py +1407 -0
  89. megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +294 -0
  90. megadetector/data_management/importers/jb_csv_to_json.py +150 -0
  91. megadetector/data_management/importers/mcgill_to_json.py +250 -0
  92. megadetector/data_management/importers/missouri_to_json.py +490 -0
  93. megadetector/data_management/importers/nacti_fieldname_adjustments.py +79 -0
  94. megadetector/data_management/importers/noaa_seals_2019.py +181 -0
  95. megadetector/data_management/importers/pc_to_json.py +365 -0
  96. megadetector/data_management/importers/plot_wni_giraffes.py +123 -0
  97. megadetector/data_management/importers/prepare-noaa-fish-data-for-lila.py +359 -0
  98. megadetector/data_management/importers/prepare_zsl_imerit.py +131 -0
  99. megadetector/data_management/importers/rspb_to_json.py +356 -0
  100. megadetector/data_management/importers/save_the_elephants_survey_A.py +320 -0
  101. megadetector/data_management/importers/save_the_elephants_survey_B.py +329 -0
  102. megadetector/data_management/importers/snapshot_safari_importer.py +758 -0
  103. megadetector/data_management/importers/snapshot_safari_importer_reprise.py +665 -0
  104. megadetector/data_management/importers/snapshot_serengeti_lila.py +1067 -0
  105. megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +150 -0
  106. megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +153 -0
  107. megadetector/data_management/importers/sulross_get_exif.py +65 -0
  108. megadetector/data_management/importers/timelapse_csv_set_to_json.py +490 -0
  109. megadetector/data_management/importers/ubc_to_json.py +399 -0
  110. megadetector/data_management/importers/umn_to_json.py +507 -0
  111. megadetector/data_management/importers/wellington_to_json.py +263 -0
  112. megadetector/data_management/importers/wi_to_json.py +442 -0
  113. megadetector/data_management/importers/zamba_results_to_md_results.py +181 -0
  114. megadetector/data_management/labelme_to_coco.py +547 -0
  115. megadetector/data_management/labelme_to_yolo.py +272 -0
  116. megadetector/data_management/lila/__init__.py +0 -0
  117. megadetector/data_management/lila/add_locations_to_island_camera_traps.py +97 -0
  118. megadetector/data_management/lila/add_locations_to_nacti.py +147 -0
  119. megadetector/data_management/lila/create_lila_blank_set.py +558 -0
  120. megadetector/data_management/lila/create_lila_test_set.py +152 -0
  121. megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
  122. megadetector/data_management/lila/download_lila_subset.py +178 -0
  123. megadetector/data_management/lila/generate_lila_per_image_labels.py +516 -0
  124. megadetector/data_management/lila/get_lila_annotation_counts.py +170 -0
  125. megadetector/data_management/lila/get_lila_image_counts.py +112 -0
  126. megadetector/data_management/lila/lila_common.py +300 -0
  127. megadetector/data_management/lila/test_lila_metadata_urls.py +132 -0
  128. megadetector/data_management/ocr_tools.py +874 -0
  129. megadetector/data_management/read_exif.py +681 -0
  130. megadetector/data_management/remap_coco_categories.py +84 -0
  131. megadetector/data_management/remove_exif.py +66 -0
  132. megadetector/data_management/resize_coco_dataset.py +189 -0
  133. megadetector/data_management/wi_download_csv_to_coco.py +246 -0
  134. megadetector/data_management/yolo_output_to_md_output.py +441 -0
  135. megadetector/data_management/yolo_to_coco.py +676 -0
  136. megadetector/detection/__init__.py +0 -0
  137. megadetector/detection/detector_training/__init__.py +0 -0
  138. megadetector/detection/detector_training/model_main_tf2.py +114 -0
  139. megadetector/detection/process_video.py +702 -0
  140. megadetector/detection/pytorch_detector.py +341 -0
  141. megadetector/detection/run_detector.py +779 -0
  142. megadetector/detection/run_detector_batch.py +1219 -0
  143. megadetector/detection/run_inference_with_yolov5_val.py +917 -0
  144. megadetector/detection/run_tiled_inference.py +934 -0
  145. megadetector/detection/tf_detector.py +189 -0
  146. megadetector/detection/video_utils.py +606 -0
  147. megadetector/postprocessing/__init__.py +0 -0
  148. megadetector/postprocessing/add_max_conf.py +64 -0
  149. megadetector/postprocessing/categorize_detections_by_size.py +163 -0
  150. megadetector/postprocessing/combine_api_outputs.py +249 -0
  151. megadetector/postprocessing/compare_batch_results.py +958 -0
  152. megadetector/postprocessing/convert_output_format.py +396 -0
  153. megadetector/postprocessing/load_api_results.py +195 -0
  154. megadetector/postprocessing/md_to_coco.py +310 -0
  155. megadetector/postprocessing/md_to_labelme.py +330 -0
  156. megadetector/postprocessing/merge_detections.py +401 -0
  157. megadetector/postprocessing/postprocess_batch_results.py +1902 -0
  158. megadetector/postprocessing/remap_detection_categories.py +170 -0
  159. megadetector/postprocessing/render_detection_confusion_matrix.py +660 -0
  160. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +211 -0
  161. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +83 -0
  162. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1631 -0
  163. megadetector/postprocessing/separate_detections_into_folders.py +730 -0
  164. megadetector/postprocessing/subset_json_detector_output.py +696 -0
  165. megadetector/postprocessing/top_folders_to_bottom.py +223 -0
  166. megadetector/taxonomy_mapping/__init__.py +0 -0
  167. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
  168. megadetector/taxonomy_mapping/map_new_lila_datasets.py +150 -0
  169. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +142 -0
  170. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +590 -0
  171. megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
  172. megadetector/taxonomy_mapping/simple_image_download.py +219 -0
  173. megadetector/taxonomy_mapping/species_lookup.py +834 -0
  174. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
  175. megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
  176. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
  177. megadetector/utils/__init__.py +0 -0
  178. megadetector/utils/azure_utils.py +178 -0
  179. megadetector/utils/ct_utils.py +612 -0
  180. megadetector/utils/directory_listing.py +246 -0
  181. megadetector/utils/md_tests.py +968 -0
  182. megadetector/utils/path_utils.py +1044 -0
  183. megadetector/utils/process_utils.py +157 -0
  184. megadetector/utils/sas_blob_utils.py +509 -0
  185. megadetector/utils/split_locations_into_train_val.py +228 -0
  186. megadetector/utils/string_utils.py +92 -0
  187. megadetector/utils/url_utils.py +323 -0
  188. megadetector/utils/write_html_image_list.py +225 -0
  189. megadetector/visualization/__init__.py +0 -0
  190. megadetector/visualization/plot_utils.py +293 -0
  191. megadetector/visualization/render_images_with_thumbnails.py +275 -0
  192. megadetector/visualization/visualization_utils.py +1536 -0
  193. megadetector/visualization/visualize_db.py +550 -0
  194. megadetector/visualization/visualize_detector_output.py +405 -0
  195. {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/METADATA +1 -1
  196. megadetector-5.0.12.dist-info/RECORD +199 -0
  197. megadetector-5.0.12.dist-info/top_level.txt +1 -0
  198. megadetector-5.0.11.dist-info/RECORD +0 -5
  199. megadetector-5.0.11.dist-info/top_level.txt +0 -1
  200. {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/LICENSE +0 -0
  201. {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/WHEEL +0 -0
@@ -0,0 +1,490 @@
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)
@@ -0,0 +1,79 @@
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
+