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
- 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)