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
- timelapse_csv_set_to_json.py
4
-
5
- Given a directory full of reasonably-consistent Timelapse-exported
6
- .csvs, assemble a CCT .json.
7
-
8
- Assumes that you have a list of all files in the directory tree, including
9
- image and .csv files.
10
-
11
- """
12
-
13
- #%% Constants and imports
14
-
15
- import uuid
16
- import json
17
- import time
18
- import re
19
- import humanfriendly
20
- import os
21
- import PIL
22
- import pandas as pd
23
- import numpy as np
24
- from tqdm import tqdm
25
-
26
- from megadetector.visualization import visualize_db
27
- from megadetector.data_management.databases import integrity_check_json_db
28
- from megadetector.utils import path_utils
29
-
30
- # Text file with relative paths to all files (images and .csv files)
31
- input_relative_file_list = ''
32
- output_file = ''
33
- preview_base = ''
34
- file_base = ''
35
- top_level_image_folder = ''
36
- contributor_name = ''
37
- csv_filename_mappings = []
38
- site_name_mappings = []
39
- csv_ignore_tokens = []
40
-
41
- expected_columns = 'File,RelativePath,Folder,Date,Time,ImageQuality,DeleteFlag,CameraLocation,StartDate,TechnicianName,Empty,Service,Species,HumanActivity,Count,AdultFemale,AdultMale,AdultUnknown,Offspring,YOY,UNK,Collars,Tags,NaturalMarks,Reaction,Illegal,GoodPicture,SecondOpinion,Comments'.\
42
- split(',')
43
- im_fields_to_copy = ['TechnicianName','Service','HumanActivity','Count','AdultFemale','AdultMale',
44
- 'AdultUnknown','Offspring','YOY','UNK','Collars','Tags','NaturalMarks','Reaction',
45
- 'Illegal','GoodPicture','SecondOpinion','Comments']
46
-
47
- ignore_fields = []
48
- required_image_regex = None
49
-
50
- category_mappings = {'none':'empty'}
51
-
52
- check_file_existence = False
53
- retrieve_image_size = False
54
-
55
-
56
- #%% Read file list, make a list of all image files and all .csv files
57
-
58
- with open(input_relative_file_list) as f:
59
- all_files = f.readlines()
60
- all_files = [x.strip() for x in all_files]
61
-
62
- image_files = set()
63
- csv_files = []
64
- non_matching_files = []
65
-
66
- for fn in all_files:
67
-
68
- fnl = fn.lower()
69
-
70
- if fnl.endswith('.csv'):
71
-
72
- csv_files.append(fn)
73
-
74
- elif (fnl.endswith('.jpg') or fnl.endswith('.png')):
75
-
76
- if required_image_regex is not None and not re.match(required_image_regex,fn):
77
- non_matching_files.append(fn)
78
- else:
79
- image_files.add(fn)
80
-
81
- for fn in image_files:
82
- assert fn.lower().endswith('.jpg')
83
-
84
- print('Found {} image files and {} .csv files ({} non-matching files)'.format(
85
- len(image_files),len(csv_files),len(non_matching_files)))
86
-
87
-
88
- #%% Verify column consistency, create a giant array with all rows from all .csv files
89
-
90
- bad_csv_files = []
91
- normalized_dataframes = []
92
-
93
- # i_csv = 0; csv_filename = csv_files[0]
94
- for i_csv,csv_filename in enumerate(csv_files):
95
-
96
- full_path = os.path.join(file_base,csv_filename)
97
- try:
98
- df = pd.read_csv(full_path)
99
- except Exception as e:
100
- if 'invalid start byte' in str(e):
101
- try:
102
- print('Read error, reverting to fallback encoding')
103
- df = pd.read_csv(full_path,encoding='latin1')
104
- except Exception as e:
105
- print('Can''t read file {}: {}'.format(csv_filename,str(e)))
106
- bad_csv_files.append(csv_filename)
107
- continue
108
-
109
- if not (len(df.columns) == len(expected_columns) and (df.columns == expected_columns).all()):
110
- extra_fields = ','.join(set(df.columns) - set(expected_columns))
111
- extra_fields = [x for x in extra_fields if x not in ignore_fields]
112
- missing_fields = ','.join(set(expected_columns) - set(df.columns))
113
- missing_fields = [x for x in missing_fields if x not in ignore_fields]
114
- if not (len(missing_fields) == 0 and len(extra_fields) == 0):
115
- print('In file {}, extra fields {}, missing fields {}'.format(csv_filename,
116
- extra_fields,missing_fields))
117
- normalized_df = df[expected_columns].copy()
118
- normalized_df['source_file'] = csv_filename
119
- normalized_dataframes.append(normalized_df)
120
-
121
- print('Ignored {} of {} csv files'.format(len(bad_csv_files),len(csv_files)))
122
- valid_csv_files = [x for x in csv_files if x not in bad_csv_files]
123
-
124
- input_metadata = pd.concat(normalized_dataframes)
125
- assert len(input_metadata.columns) == 1 + len(expected_columns)
126
-
127
- print('Concatenated all .csv files into a dataframe with {} rows'.format(len(input_metadata)))
128
-
129
-
130
- #%% Prepare some data structures we'll need for mapping image rows in .csv files to actual image files
131
-
132
- # Enumerate all folders containing image files
133
- all_image_folders = set()
134
-
135
- for fn in image_files:
136
- dn = os.path.dirname(fn)
137
- all_image_folders.add(dn)
138
-
139
- print('Enumerated {} unique image folders'.format(len(all_image_folders)))
140
-
141
- # In this data set, a site folder looks like:
142
- #
143
- # Processed Images\\site_name
144
-
145
- site_folders = set()
146
- for image_folder in all_image_folders:
147
- tokens = path_utils.split_path(image_folder)
148
- site_folders.add(tokens[0] + '/' + tokens[1])
149
-
150
-
151
- #%% Map .csv files to candidate camera folders
152
-
153
- csv_filename_to_camera_folder = {}
154
-
155
- # fn = valid_csv_files[0]
156
- for fn_original in valid_csv_files:
157
-
158
- fn = fn_original
159
- if any(s in fn for s in csv_ignore_tokens):
160
- continue
161
-
162
- for mapping in csv_filename_mappings:
163
- fn = fn.replace(mapping[0],mapping[1])
164
-
165
- csv_filename = os.path.basename(fn)
166
- pat = '^(?P<site>[^_]+)_(?P<cameranum>[^_]+)_'
167
- re_result = re.search(pat,csv_filename)
168
- if re_result is None:
169
- print('Couldn''t match tokens in {}'.format(csv_filename))
170
- continue
171
- site = re_result.group('site')
172
-
173
- for mapping in site_name_mappings:
174
- site = site.replace(mapping[0],mapping[1])
175
-
176
- cameranum = re_result.group('cameranum')
177
-
178
- site_folder = top_level_image_folder + '/' + site
179
-
180
- # Some site folders appear as "XXNNNN", some appear as "XXNNNN_complete"
181
- if site_folder not in site_folders:
182
- site = site + '_complete'
183
- site_folder = top_level_image_folder + '/' + site
184
- if site_folder not in site_folders:
185
- print('Could not find site folder for {}'.format(fn))
186
- continue
187
-
188
- camera_folder = top_level_image_folder + '/' + site + '/Camera_' + str(cameranum)
189
-
190
- b_found_camera_folder = False
191
-
192
- for candidate_camera_folder in all_image_folders:
193
-
194
- if candidate_camera_folder.startswith(camera_folder):
195
- b_found_camera_folder = True
196
- break
197
-
198
- if not b_found_camera_folder:
199
- print('Could not find camera folder {} for csv {}'.format(camera_folder,fn))
200
- continue
201
-
202
- assert fn not in csv_filename_to_camera_folder
203
- csv_filename_to_camera_folder[fn_original] = camera_folder
204
-
205
- # ...for each .csv file
206
-
207
- print('Successfully mapped {} of {} csv files to camera folders'.format(len(csv_filename_to_camera_folder),
208
- len(valid_csv_files)))
209
-
210
- for fn in valid_csv_files:
211
-
212
- if any(s in fn for s in csv_ignore_tokens):
213
- continue
214
-
215
- if fn not in csv_filename_to_camera_folder:
216
- print('No camera folder mapping for {}'.format(fn))
217
-
218
-
219
- #%% Map camera folders to candidate image folders
220
-
221
- camera_folders_to_image_folders = {}
222
-
223
- for camera_folder in csv_filename_to_camera_folder.values():
224
-
225
- for image_folder in all_image_folders:
226
- if image_folder.startswith(camera_folder):
227
- camera_folders_to_image_folders.setdefault(camera_folder,[]).append(image_folder)
228
-
229
-
230
- #%% Main loop over labels (prep)
231
-
232
- start_time = time.time()
233
-
234
- relative_path_to_image = {}
235
- image_id_to_image = {}
236
-
237
- images = []
238
- annotations = []
239
- category_name_to_category = {}
240
- files_missing_from_file_list = []
241
- files_missing_on_disk = []
242
-
243
- duplicate_image_ids = set()
244
-
245
- # Force the empty category to be ID 0
246
- empty_category = {}
247
- empty_category['name'] = 'empty'
248
- empty_category['id'] = 0
249
- category_name_to_category['empty'] = empty_category
250
-
251
- next_category_id = 1
252
-
253
- ignored_csv_files = set()
254
- ignored_image_folders = set()
255
-
256
- # Images that are marked empty and also have a species label
257
- ambiguous_images = []
258
-
259
-
260
- #%% Main loop over labels (loop)
261
-
262
- # i_row = 0; row = input_metadata.iloc[i_row]
263
- for i_row,row in tqdm(input_metadata.iterrows(),total=len(input_metadata)):
264
- # for i_row,row in input_metadata.iterrows():
265
-
266
- image_filename = row['File']
267
- image_folder = row['RelativePath']
268
- if isinstance(image_folder,float):
269
- assert np.isnan(image_folder)
270
- image_folder = row['Folder']
271
- image_folder = image_folder.replace('\\','/')
272
-
273
- # Usually this is just a single folder name, sometimes it's a full path,
274
- # which we don't want
275
- image_folder = path_utils.split_path(image_folder)[-1]
276
- csv_filename = row['source_file']
277
-
278
- if any(s in csv_filename for s in csv_ignore_tokens):
279
- continue
280
-
281
- if csv_filename not in csv_filename_to_camera_folder:
282
- if csv_filename not in ignored_csv_files:
283
- print('No camera folder for {}'.format(csv_filename))
284
- assert csv_filename in valid_csv_files
285
- ignored_csv_files.add(csv_filename)
286
- continue
287
-
288
- camera_folder = csv_filename_to_camera_folder[csv_filename]
289
- candidate_image_folders = camera_folders_to_image_folders[camera_folder]
290
-
291
- image_folder_relative_path = None
292
- for candidate_image_folder in candidate_image_folders:
293
- if candidate_image_folder.endswith(image_folder):
294
- image_folder_relative_path = candidate_image_folder
295
- if image_folder_relative_path is None:
296
- camera_image_folder = camera_folder + '_' + image_folder
297
- if camera_image_folder not in ignored_image_folders:
298
- print('No image folder for {}'.format(camera_image_folder))
299
- ignored_image_folders.add(camera_image_folder)
300
- continue
301
-
302
- image_relative_path = image_folder_relative_path + '/' + image_filename
303
- if image_relative_path not in image_files:
304
- files_missing_from_file_list.append(image_relative_path)
305
- continue
306
-
307
- image_id = image_relative_path.replace('_','~').replace('/','_').replace('\\','_')
308
-
309
- if image_id in image_id_to_image:
310
-
311
- im = image_id_to_image[image_id]
312
- assert im['id'] == image_id
313
- duplicate_image_ids.add(image_id)
314
-
315
- else:
316
-
317
- im = {}
318
- im['id'] = image_id
319
- im['file_name'] = image_relative_path
320
- im['seq_id'] = '-1'
321
- im['datetime'] = row['Date'] + ' ' + row['Time']
322
- im['location'] = row['CameraLocation']
323
-
324
- for col in im_fields_to_copy:
325
- im[col.lower()] = row[col]
326
-
327
- for k in im:
328
- if isinstance(im[k],float) and np.isnan(im[k]):
329
- im[k] = ''
330
-
331
- images.append(im)
332
- relative_path_to_image[image_relative_path] = im
333
- image_id_to_image[image_id] = im
334
-
335
- if check_file_existence or retrieve_image_size:
336
-
337
- image_full_path = os.path.join(file_base,image_relative_path)
338
-
339
- # Check whether this file exists on disk
340
- if check_file_existence:
341
- if not os.path.isfile(image_full_path):
342
- files_missing_on_disk.append(image_relative_path)
343
-
344
- # Retrieve image width and height
345
- if retrieve_image_size:
346
- pil_image = PIL.Image.open(image_full_path)
347
- width, height = pil_image.size
348
- im['width'] = width
349
- im['height'] = height
350
-
351
- category_name = row['Species']
352
- if isinstance(category_name,float):
353
- assert np.isnan(category_name)
354
- category_name = None
355
- else:
356
- category_name = category_name.lower()
357
-
358
- empty_token = row['Empty']
359
- if empty_token == True:
360
- if category_name is not None:
361
- category_name = 'ambiguous'
362
- ambiguous_images.append(im)
363
- else:
364
- category_name = 'empty'
365
- else:
366
- assert empty_token == False
367
- if category_name is None:
368
- category_name = 'unlabeled'
369
-
370
- if category_name in category_mappings:
371
- category_name = category_mappings[category_name]
372
-
373
- if category_name not in category_name_to_category:
374
- category = {}
375
- category['name'] = category_name
376
- category['id'] = next_category_id
377
- next_category_id += 1
378
- category_name_to_category[category_name] = category
379
- else:
380
- category = category_name_to_category[category_name]
381
-
382
- category_id = category['id']
383
-
384
- # Create an annotation
385
- ann = {}
386
-
387
- # The Internet tells me this guarantees uniqueness to a reasonable extent, even
388
- # beyond the sheer improbability of collisions.
389
- ann['id'] = str(uuid.uuid1())
390
- ann['image_id'] = im['id']
391
- ann['category_id'] = category_id
392
-
393
- annotations.append(ann)
394
-
395
- # ...for each row in the big table of concatenated .csv files
396
-
397
- categories = list(category_name_to_category.values())
398
-
399
- elapsed = time.time() - start_time
400
- print('Finished verifying file loop in {}, {} images, {} missing images, {} repeat labels, {} ambiguous labels'.format(
401
- humanfriendly.format_timespan(elapsed), len(images), len(files_missing_from_file_list),
402
- len(duplicate_image_ids), len(ambiguous_images)))
403
-
404
-
405
- #%% Fix cases where an image was annotated as 'unlabeled' and as something else
406
-
407
- image_id_to_annotations = {}
408
- for ann in annotations:
409
- image_id = ann['image_id']
410
- image_id_to_annotations.setdefault(image_id,[]).append(ann)
411
-
412
- valid_annotations = []
413
- unlabeled_id = category_name_to_category['unlabeled']['id']
414
-
415
- for ann in annotations:
416
-
417
- if ann['category_id'] != unlabeled_id:
418
- valid_annotations.append(ann)
419
- continue
420
-
421
- # This annotation is 'unlabeled'
422
- image_id = ann['image_id']
423
- image_annotations = image_id_to_annotations[image_id]
424
- image_categories = list(set([a['category_id'] for a in image_annotations]))
425
-
426
- # Was there another category associated with this image?
427
- assert unlabeled_id in image_categories
428
- if len(image_categories) > 1:
429
- continue
430
-
431
- valid_annotations.append(ann)
432
-
433
- print('Removed {} redundant unlabeled annotations'.format(len(annotations)-len(valid_annotations)))
434
-
435
-
436
- #%% Check for un-annnotated images
437
-
438
- # Enumerate all images
439
- # list(relative_path_to_image.keys())[0]
440
-
441
- unmatched_files = []
442
-
443
- for i_image,image_path in enumerate(image_files):
444
-
445
- if image_path not in relative_path_to_image:
446
- unmatched_files.append(image_path)
447
-
448
- print('Finished checking {} images to make sure they\'re in the metadata, found {} un-annotated images'.format(
449
- len(image_files),len(unmatched_files)))
450
-
451
-
452
- #%% Create info struct
453
-
454
- info = {}
455
- info['year'] = 2019
456
- info['version'] = 1
457
- info['description'] = 'COCO style database'
458
- info['secondary_contributor'] = 'Converted to COCO .json by Dan Morris'
459
- info['contributor'] = contributor_name
460
-
461
-
462
- #%% Write output
463
-
464
- json_data = {}
465
- json_data['images'] = images
466
- json_data['annotations'] = annotations
467
- json_data['categories'] = categories
468
- json_data['info'] = info
469
- json.dump(json_data, open(output_file,'w'), indent=1)
470
-
471
- print('Finished writing .json file with {} images, {} annotations, and {} categories'.format(
472
- len(images),len(annotations),len(categories)))
473
-
474
-
475
- #%% Validate the database's integrity
476
-
477
- options = integrity_check_json_db.IntegrityCheckOptions()
478
- sortedCategories,data = integrity_check_json_db.integrity_check_json_db(output_file, options)
479
-
480
-
481
- #%% Render a bunch of images to make sure the labels got carried along correctly
482
-
483
- options = visualize_db.DbVizOptions()
484
- options.num_to_visualize = 1000
485
- options.parallelize_rendering = True
486
- options.sort_by_filename = False
487
- options.classes_to_exclude = ['unlabeled','empty','ambiguous']
488
-
489
- html_output_file,data = visualize_db.visualize_db(output_file,preview_base,file_base,options)
490
- os.startfile(html_output_file)