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,340 +1,344 @@
1
- """
2
-
3
- mewc_to_md.py
4
-
5
- Converts the output of the MEWC inference scripts to the MD output format.
6
-
7
- """
8
-
9
- #%% Imports and constants
10
-
11
- import os
12
- import json
13
- import pandas as pd
14
-
15
- from copy import deepcopy
16
- from collections import defaultdict
17
- from megadetector.utils.ct_utils import sort_list_of_dicts_by_key, invert_dictionary # noqa
18
- from megadetector.utils.path_utils import recursive_file_list
19
-
20
- from megadetector.postprocessing.validate_batch_results import \
21
- ValidateBatchResultsOptions, validate_batch_results
22
-
23
- default_mewc_mount_prefix = '/images/'
24
- default_mewc_category_name_column = 'class_id'
25
-
26
-
27
- #%% Functions
28
-
29
- def mewc_to_md(mewc_input_folder,
30
- output_file=None,
31
- mount_prefix=default_mewc_mount_prefix,
32
- category_name_column=default_mewc_category_name_column,
33
- mewc_out_filename='mewc_out.csv',
34
- md_out_filename='md_out.json'):
35
- """
36
-
37
- Args:
38
- mewc_input_folder (str): the folder we'll search for MEWC output files
39
- output_file (str, optional): .json file to write with class information
40
- mount_prefix (str, optional): string to remove from all filenames in the MD
41
- .json file, typically the prefix used to mount the image folder.
42
- category_name_column (str, optional): column in the MEWC results .csv to use for
43
- category naming.
44
-
45
- Returns:
46
- dict: an MD-formatted dict, the same as what's written to [output_file]
47
- """
48
-
49
- ##%% Read input files
50
-
51
- assert os.path.isdir(mewc_input_folder), \
52
- 'Could not find folder {}'.format(mewc_input_folder)
53
-
54
-
55
- ##%% Find MEWC output files
56
-
57
- relative_path_to_mewc_info = {}
58
-
59
- print('Listing files in folder {}'.format(mewc_input_folder))
60
- all_files_relative = set(recursive_file_list(mewc_input_folder,return_relative_paths=True))
61
-
62
- for fn_relative in all_files_relative:
63
- if fn_relative.endswith(mewc_out_filename):
64
- folder_relative = '/'.join(fn_relative.split('/')[:-1])
65
- assert folder_relative not in relative_path_to_mewc_info
66
- md_output_file_relative = os.path.join(folder_relative,md_out_filename).replace('\\','/')
67
- assert md_output_file_relative in all_files_relative, \
68
- 'Could not find MD output file {} to match to {}'.format(
69
- md_output_file_relative,fn_relative)
70
- relative_path_to_mewc_info[folder_relative] = \
71
- {'mewc_predict_file':fn_relative,'md_file':md_output_file_relative}
72
-
73
- del folder_relative
74
-
75
- print('Found {} MEWC results files'.format(len(relative_path_to_mewc_info)))
76
-
77
-
78
- ##%% Prepare to loop over results files
79
-
80
- md_results_all = {}
81
- md_results_all['images'] = []
82
- md_results_all['detection_categories'] = {}
83
- md_results_all['classification_categories'] = {}
84
- md_results_all['info'] = None
85
-
86
- classification_category_name_to_id = {}
87
-
88
-
89
- ##%% Loop over results files
90
-
91
- # relative_folder = next(iter(relative_path_to_mewc_info.keys()))
92
- for relative_folder in relative_path_to_mewc_info:
93
-
94
- ##%%
95
-
96
- mewc_info = relative_path_to_mewc_info[relative_folder]
97
- mewc_csv_fn_abs = os.path.join(mewc_input_folder,mewc_info['mewc_predict_file'])
98
- mewc_md_fn_abs = os.path.join(mewc_input_folder,mewc_info['md_file'])
99
-
100
- mewc_classification_info = pd.read_csv(mewc_csv_fn_abs)
101
- mewc_classification_info = mewc_classification_info.to_dict('records')
102
-
103
- assert os.path.isfile(mewc_md_fn_abs), \
104
- 'Could not find file {}'.format(mewc_md_fn_abs)
105
- with open(mewc_md_fn_abs,'r') as f:
106
- md_results = json.load(f)
107
-
108
-
109
- ##%% Remove the mount prefix from MD files if necessary
110
- if mount_prefix is not None and len(mount_prefix) > 0:
111
-
112
- n_files_without_mount_prefix = 0
113
-
114
- # im = md_results['images'][0]
115
- for im in md_results['images']:
116
- if not im['file'].startswith(mount_prefix):
117
- n_files_without_mount_prefix += 1
118
- else:
119
- im['file'] = im['file'].replace(mount_prefix,'',1)
120
-
121
- if n_files_without_mount_prefix > 0:
122
- print('Warning {} of {} files in the MD results did not include the mount prefix {}'.format(
123
- n_files_without_mount_prefix,len(md_results['images']),mount_prefix))
124
-
125
-
126
- ##%% Convert MEWC snip IDs to image files
127
-
128
- # r = mewc_classification_info[0]
129
- for r in mewc_classification_info:
130
-
131
- # E.g. "IMG0-0.jpg"
132
- snip_file = r['filename']
133
-
134
- # E.g. "IMG0-0"
135
- snip_file_no_ext = os.path.splitext(snip_file)[0]
136
- ext = os.path.splitext(snip_file)[1] # noqa
137
-
138
- tokens = snip_file_no_ext.split('-')
139
-
140
- if len(tokens) == 1:
141
- print('Warning: in folder {}, detection ID not found in snip filename {}, skipping'.format(
142
- relative_folder,snip_file_no_ext))
143
- r['image_filename_without_extension'] = snip_file_no_ext
144
- r['snip_id'] = None
145
-
146
- continue
147
-
148
- filename_without_snip_id = '-'.join(tokens[0:-1])
149
- snip_id = int(tokens[-1])
150
- image_filename_without_extension = filename_without_snip_id
151
-
152
- r['image_filename_without_extension'] = image_filename_without_extension
153
- r['snip_id'] = snip_id
154
-
155
- # ...for each MEWC result record
156
-
157
-
158
- ##%% Make sure MD results and MEWC results refer to the same files
159
-
160
- images_in_md_results_no_extension = \
161
- set([os.path.splitext(im['file'])[0] for im in md_results['images']])
162
- images_in_mewc_results_no_extension = set(r['image_filename_without_extension'] \
163
- for r in mewc_classification_info)
164
-
165
- # All files with classification results should also have detection results
166
- for fn in images_in_mewc_results_no_extension:
167
- assert fn in images_in_md_results_no_extension, \
168
- 'Error: file {} is present in mewc-predict results, but not in MD results'.format(fn)
169
-
170
- # This is just a note to self: no classification results are present for empty images
171
- if False:
172
- for fn in images_in_md_results_no_extension:
173
- if fn not in images_in_mewc_results_no_extension:
174
- print('Warning: file {}/{} is present in MD results, but not in mewc-predict results'.format(
175
- relative_folder,fn))
176
-
177
-
178
- ##%% Validate images
179
-
180
- for im in md_results['images']:
181
- fn_relative = im['file']
182
- fn_abs = os.path.join(mewc_input_folder,relative_folder,fn_relative)
183
- if not os.path.isfile(fn_abs):
184
- print('Warning: image file {} does not exist'.format(fn_abs))
185
-
186
-
187
- ##%% Map filenames to MEWC results
188
-
189
- image_id_to_mewc_records = defaultdict(list)
190
- for r in mewc_classification_info:
191
- image_id_to_mewc_records[r['image_filename_without_extension']].append(r)
192
-
193
-
194
- ##%% Add classification info to MD results
195
-
196
- # im = md_results['images'][0]
197
- for im in md_results['images']:
198
-
199
- if ('detections' not in im) or (im['detections'] is None) or (len(im['detections']) == 0):
200
- continue
201
-
202
- detections = im['detections']
203
-
204
- # *Don't* sort by confidence, it looks like snip IDs use the original sort order
205
- # detections = sort_list_of_dicts_by_key(detections,'conf',reverse=True)
206
-
207
- # This is just a debug assist, so I can run this cell more than once
208
- for det in detections:
209
- det['classifications'] = []
210
-
211
- image_id = os.path.splitext(im['file'])[0]
212
- mewc_records_this_image = image_id_to_mewc_records[image_id]
213
-
214
- # r = mewc_records_this_image[0]
215
- for r in mewc_records_this_image:
216
-
217
- if r['snip_id'] is None:
218
- continue
219
-
220
- category_name = r[category_name_column]
221
-
222
- # This is a *global* list of category mappings, across all mewc .csv files
223
- if category_name not in classification_category_name_to_id:
224
- category_id = str(len(classification_category_name_to_id))
225
- classification_category_name_to_id[category_name] = category_id
226
- else:
227
- category_id = classification_category_name_to_id[category_name]
228
-
229
- snip_id = r['snip_id']
230
- if snip_id >= len(detections):
231
- print('Warning: image {} has a classified snip ID of {}, but only {} detections are present'.format(
232
- image_id,snip_id,len(detections)))
233
- continue
234
-
235
- det = detections[snip_id]
236
-
237
- if 'classifications' not in det:
238
- det['classifications'] = []
239
- det['classifications'].append([category_id,r['prob']])
240
-
241
- # ...for each classification in this image
242
-
243
- # ...for each image
244
-
245
- ##%% Map MD results to the global level
246
-
247
- if md_results_all['info'] is None:
248
- md_results_all['info'] = md_results['info']
249
-
250
- for category_id in md_results['detection_categories']:
251
- if category_id not in md_results_all['detection_categories']:
252
- md_results_all['detection_categories'][category_id] = \
253
- md_results['detection_categories'][category_id]
254
- else:
255
- assert md_results_all['detection_categories'][category_id] == \
256
- md_results['detection_categories'][category_id], \
257
- 'MD results present with incompatible detection categories'
258
-
259
- # im = md_results['images'][0]
260
- for im in md_results['images']:
261
- im_copy = deepcopy(im)
262
- im_copy['file'] = os.path.join(relative_folder,im['file']).replace('\\','/')
263
- md_results_all['images'].append(im_copy)
264
-
265
- # ...for each folder that contains MEWC results
266
-
267
- del md_results
268
-
269
- ##%% Write output
270
-
271
- md_results_all['classification_categories'] = invert_dictionary(classification_category_name_to_id)
272
-
273
- if output_file is not None:
274
- output_dir = os.path.dirname(output_file)
275
- os.makedirs(output_dir,exist_ok=True)
276
- with open(output_file,'w') as f:
277
- json.dump(md_results_all,f,indent=1)
278
-
279
- validation_options = ValidateBatchResultsOptions()
280
- validation_options.check_image_existence = True
281
- validation_options.relative_path_base = mewc_input_folder
282
- validation_options.raise_errors = True
283
- validation_results = validate_batch_results(output_file,validation_options) # noqa
284
-
285
- # ...def mewc_to_md(...)
286
-
287
-
288
- #%% Interactive driver
289
-
290
- if False:
291
-
292
- pass
293
-
294
- #%%
295
-
296
- mewc_input_folder = r'G:\temp\mewc-test'
297
- mount_prefix = '/images/'
298
- output_file = os.path.join(mewc_input_folder,'results_with_classes.json')
299
-
300
- _ = mewc_to_md(mewc_input_folder=mewc_input_folder,
301
- output_file=output_file,
302
- mount_prefix=mount_prefix,
303
- category_name_column='class_id')
304
-
305
-
306
- #%% Command-line driver
307
-
308
- import sys
309
- import argparse
310
-
311
- def main():
312
-
313
- parser = argparse.ArgumentParser()
314
-
315
- parser.add_argument(
316
- 'input_folder',type=str,
317
- help='Folder containing images and MEWC .json/.csv files')
318
- parser.add_argument(
319
- 'output_file',type=str,
320
- help='.json file where output will be written')
321
- parser.add_argument(
322
- '--mount_prefix',type=str,default=default_mewc_mount_prefix,
323
- help='prefix to remove from each filename in MEWC results, typically the Docker mount point')
324
- parser.add_argument(
325
- '--category_name_column',type=str,default=default_mewc_category_name_column,
326
- help='column in the MEWC .csv file to use for category names')
327
-
328
- if len(sys.argv[1:]) == 0:
329
- parser.print_help()
330
- parser.exit()
331
-
332
- args = parser.parse_args()
333
-
334
- _ = mewc_to_md(mewc_input_folder=args.input_folder,
335
- output_file=args.output_file,
336
- mount_prefix=args.mount_prefix,
337
- category_name_column=args.category_name_column)
338
-
339
- if __name__ == '__main__':
340
- main()
1
+ """
2
+
3
+ mewc_to_md.py
4
+
5
+ Converts the output of the MEWC inference scripts to the MD output format.
6
+
7
+ """
8
+
9
+ #%% Imports and constants
10
+
11
+ import os
12
+ import json
13
+ import pandas as pd
14
+ import sys
15
+ import argparse
16
+
17
+ from copy import deepcopy
18
+ from collections import defaultdict
19
+ from megadetector.utils.ct_utils import sort_list_of_dicts_by_key, invert_dictionary # noqa
20
+ from megadetector.utils.path_utils import recursive_file_list
21
+
22
+ from megadetector.postprocessing.validate_batch_results import \
23
+ ValidateBatchResultsOptions, validate_batch_results
24
+
25
+ default_mewc_mount_prefix = '/images/'
26
+ default_mewc_category_name_column = 'class_id'
27
+
28
+
29
+ #%% Functions
30
+
31
+ def mewc_to_md(mewc_input_folder,
32
+ output_file=None,
33
+ mount_prefix=default_mewc_mount_prefix,
34
+ category_name_column=default_mewc_category_name_column,
35
+ mewc_out_filename='mewc_out.csv',
36
+ md_out_filename='md_out.json'):
37
+ """
38
+ Converts the output of the MEWC inference scripts to the MD output format.
39
+
40
+ Args:
41
+ mewc_input_folder (str): the folder we'll search for MEWC output files
42
+ output_file (str, optional): .json file to write with class information
43
+ mount_prefix (str, optional): string to remove from all filenames in the MD
44
+ .json file, typically the prefix used to mount the image folder.
45
+ category_name_column (str, optional): column in the MEWC results .csv to use for
46
+ category naming.
47
+ mewc_out_filename (str, optional): MEWC-formatted .csv file that should be
48
+ in [mewc_input_folder]
49
+ md_out_filename (str, optional): MD-formatted .json file (without classification
50
+ information) that should be in [mewc_input_folder]
51
+
52
+ Returns:
53
+ dict: an MD-formatted dict, the same as what's written to [output_file]
54
+ """
55
+
56
+ ##%% Read input files
57
+
58
+ assert os.path.isdir(mewc_input_folder), \
59
+ 'Could not find folder {}'.format(mewc_input_folder)
60
+
61
+
62
+ ##%% Find MEWC output files
63
+
64
+ relative_path_to_mewc_info = {}
65
+
66
+ print('Listing files in folder {}'.format(mewc_input_folder))
67
+ all_files_relative = set(recursive_file_list(mewc_input_folder,return_relative_paths=True))
68
+
69
+ for fn_relative in all_files_relative:
70
+ if fn_relative.endswith(mewc_out_filename):
71
+ folder_relative = '/'.join(fn_relative.split('/')[:-1])
72
+ assert folder_relative not in relative_path_to_mewc_info
73
+ md_output_file_relative = os.path.join(folder_relative,md_out_filename).replace('\\','/')
74
+ assert md_output_file_relative in all_files_relative, \
75
+ 'Could not find MD output file {} to match to {}'.format(
76
+ md_output_file_relative,fn_relative)
77
+ relative_path_to_mewc_info[folder_relative] = \
78
+ {'mewc_predict_file':fn_relative,'md_file':md_output_file_relative}
79
+
80
+ del folder_relative
81
+
82
+ print('Found {} MEWC results files'.format(len(relative_path_to_mewc_info)))
83
+
84
+
85
+ ##%% Prepare to loop over results files
86
+
87
+ md_results_all = {}
88
+ md_results_all['images'] = []
89
+ md_results_all['detection_categories'] = {}
90
+ md_results_all['classification_categories'] = {}
91
+ md_results_all['info'] = None
92
+
93
+ classification_category_name_to_id = {}
94
+
95
+
96
+ ##%% Loop over results files
97
+
98
+ # relative_folder = next(iter(relative_path_to_mewc_info.keys()))
99
+ for relative_folder in relative_path_to_mewc_info:
100
+
101
+ ##%%
102
+
103
+ mewc_info = relative_path_to_mewc_info[relative_folder]
104
+ mewc_csv_fn_abs = os.path.join(mewc_input_folder,mewc_info['mewc_predict_file'])
105
+ mewc_md_fn_abs = os.path.join(mewc_input_folder,mewc_info['md_file'])
106
+
107
+ mewc_classification_info = pd.read_csv(mewc_csv_fn_abs)
108
+ mewc_classification_info = mewc_classification_info.to_dict('records')
109
+
110
+ assert os.path.isfile(mewc_md_fn_abs), \
111
+ 'Could not find file {}'.format(mewc_md_fn_abs)
112
+ with open(mewc_md_fn_abs,'r') as f:
113
+ md_results = json.load(f)
114
+
115
+
116
+ ##%% Remove the mount prefix from MD files if necessary
117
+ if mount_prefix is not None and len(mount_prefix) > 0:
118
+
119
+ n_files_without_mount_prefix = 0
120
+
121
+ # im = md_results['images'][0]
122
+ for im in md_results['images']:
123
+ if not im['file'].startswith(mount_prefix):
124
+ n_files_without_mount_prefix += 1
125
+ else:
126
+ im['file'] = im['file'].replace(mount_prefix,'',1)
127
+
128
+ if n_files_without_mount_prefix > 0:
129
+ print('Warning {} of {} files in the MD results did not include the mount prefix {}'.format(
130
+ n_files_without_mount_prefix,len(md_results['images']),mount_prefix))
131
+
132
+
133
+ ##%% Convert MEWC snip IDs to image files
134
+
135
+ # r = mewc_classification_info[0]
136
+ for r in mewc_classification_info:
137
+
138
+ # E.g. "IMG0-0.jpg"
139
+ snip_file = r['filename']
140
+
141
+ # E.g. "IMG0-0"
142
+ snip_file_no_ext = os.path.splitext(snip_file)[0]
143
+ ext = os.path.splitext(snip_file)[1] # noqa
144
+
145
+ tokens = snip_file_no_ext.split('-')
146
+
147
+ if len(tokens) == 1:
148
+ print('Warning: in folder {}, detection ID not found in snip filename {}, skipping'.format(
149
+ relative_folder,snip_file_no_ext))
150
+ r['image_filename_without_extension'] = snip_file_no_ext
151
+ r['snip_id'] = None
152
+
153
+ continue
154
+
155
+ filename_without_snip_id = '-'.join(tokens[0:-1])
156
+ snip_id = int(tokens[-1])
157
+ image_filename_without_extension = filename_without_snip_id
158
+
159
+ r['image_filename_without_extension'] = image_filename_without_extension
160
+ r['snip_id'] = snip_id
161
+
162
+ # ...for each MEWC result record
163
+
164
+
165
+ ##%% Make sure MD results and MEWC results refer to the same files
166
+
167
+ images_in_md_results_no_extension = \
168
+ set([os.path.splitext(im['file'])[0] for im in md_results['images']])
169
+ images_in_mewc_results_no_extension = set(r['image_filename_without_extension'] \
170
+ for r in mewc_classification_info)
171
+
172
+ # All files with classification results should also have detection results
173
+ for fn in images_in_mewc_results_no_extension:
174
+ assert fn in images_in_md_results_no_extension, \
175
+ 'Error: file {} is present in mewc-predict results, but not in MD results'.format(fn)
176
+
177
+ # This is just a note to self: no classification results are present for empty images
178
+ if False:
179
+ for fn in images_in_md_results_no_extension:
180
+ if fn not in images_in_mewc_results_no_extension:
181
+ print('Warning: file {}/{} is present in MD results, but not in mewc-predict results'.format(
182
+ relative_folder,fn))
183
+
184
+
185
+ ##%% Validate images
186
+
187
+ for im in md_results['images']:
188
+ fn_relative = im['file']
189
+ fn_abs = os.path.join(mewc_input_folder,relative_folder,fn_relative)
190
+ if not os.path.isfile(fn_abs):
191
+ print('Warning: image file {} does not exist'.format(fn_abs))
192
+
193
+
194
+ ##%% Map filenames to MEWC results
195
+
196
+ image_id_to_mewc_records = defaultdict(list)
197
+ for r in mewc_classification_info:
198
+ image_id_to_mewc_records[r['image_filename_without_extension']].append(r)
199
+
200
+
201
+ ##%% Add classification info to MD results
202
+
203
+ # im = md_results['images'][0]
204
+ for im in md_results['images']:
205
+
206
+ if ('detections' not in im) or (im['detections'] is None) or (len(im['detections']) == 0):
207
+ continue
208
+
209
+ detections = im['detections']
210
+
211
+ # *Don't* sort by confidence, it looks like snip IDs use the original sort order
212
+ # detections = sort_list_of_dicts_by_key(detections,'conf',reverse=True)
213
+
214
+ # This is just a debug assist, so I can run this cell more than once
215
+ for det in detections:
216
+ det['classifications'] = []
217
+
218
+ image_id = os.path.splitext(im['file'])[0]
219
+ mewc_records_this_image = image_id_to_mewc_records[image_id]
220
+
221
+ # r = mewc_records_this_image[0]
222
+ for r in mewc_records_this_image:
223
+
224
+ if r['snip_id'] is None:
225
+ continue
226
+
227
+ category_name = r[category_name_column]
228
+
229
+ # This is a *global* list of category mappings, across all mewc .csv files
230
+ if category_name not in classification_category_name_to_id:
231
+ category_id = str(len(classification_category_name_to_id))
232
+ classification_category_name_to_id[category_name] = category_id
233
+ else:
234
+ category_id = classification_category_name_to_id[category_name]
235
+
236
+ snip_id = r['snip_id']
237
+ if snip_id >= len(detections):
238
+ print('Warning: image {} has a classified snip ID of {}, but only {} detections are present'.format(
239
+ image_id,snip_id,len(detections)))
240
+ continue
241
+
242
+ det = detections[snip_id]
243
+
244
+ if 'classifications' not in det:
245
+ det['classifications'] = []
246
+ det['classifications'].append([category_id,r['prob']])
247
+
248
+ # ...for each classification in this image
249
+
250
+ # ...for each image
251
+
252
+ ##%% Map MD results to the global level
253
+
254
+ if md_results_all['info'] is None:
255
+ md_results_all['info'] = md_results['info']
256
+
257
+ for category_id in md_results['detection_categories']:
258
+ if category_id not in md_results_all['detection_categories']:
259
+ md_results_all['detection_categories'][category_id] = \
260
+ md_results['detection_categories'][category_id]
261
+ else:
262
+ assert md_results_all['detection_categories'][category_id] == \
263
+ md_results['detection_categories'][category_id], \
264
+ 'MD results present with incompatible detection categories'
265
+
266
+ # im = md_results['images'][0]
267
+ for im in md_results['images']:
268
+ im_copy = deepcopy(im)
269
+ im_copy['file'] = os.path.join(relative_folder,im['file']).replace('\\','/')
270
+ md_results_all['images'].append(im_copy)
271
+
272
+ # ...for each folder that contains MEWC results
273
+
274
+ del md_results
275
+
276
+ ##%% Write output
277
+
278
+ md_results_all['classification_categories'] = invert_dictionary(classification_category_name_to_id)
279
+
280
+ if output_file is not None:
281
+ output_dir = os.path.dirname(output_file)
282
+ os.makedirs(output_dir,exist_ok=True)
283
+ with open(output_file,'w') as f:
284
+ json.dump(md_results_all,f,indent=1)
285
+
286
+ validation_options = ValidateBatchResultsOptions()
287
+ validation_options.check_image_existence = True
288
+ validation_options.relative_path_base = mewc_input_folder
289
+ validation_options.raise_errors = True
290
+ validation_results = validate_batch_results(output_file,validation_options) # noqa
291
+
292
+ # ...def mewc_to_md(...)
293
+
294
+
295
+ #%% Interactive driver
296
+
297
+ if False:
298
+
299
+ pass
300
+
301
+ #%%
302
+
303
+ mewc_input_folder = r'G:\temp\mewc-test'
304
+ mount_prefix = '/images/'
305
+ output_file = os.path.join(mewc_input_folder,'results_with_classes.json')
306
+
307
+ _ = mewc_to_md(mewc_input_folder=mewc_input_folder,
308
+ output_file=output_file,
309
+ mount_prefix=mount_prefix,
310
+ category_name_column='class_id')
311
+
312
+
313
+ #%% Command-line driver
314
+
315
+ def main(): # noqa
316
+
317
+ parser = argparse.ArgumentParser()
318
+
319
+ parser.add_argument(
320
+ 'input_folder',type=str,
321
+ help='Folder containing images and MEWC .json/.csv files')
322
+ parser.add_argument(
323
+ 'output_file',type=str,
324
+ help='.json file where output will be written')
325
+ parser.add_argument(
326
+ '--mount_prefix',type=str,default=default_mewc_mount_prefix,
327
+ help='prefix to remove from each filename in MEWC results, typically the Docker mount point')
328
+ parser.add_argument(
329
+ '--category_name_column',type=str,default=default_mewc_category_name_column,
330
+ help='column in the MEWC .csv file to use for category names')
331
+
332
+ if len(sys.argv[1:]) == 0:
333
+ parser.print_help()
334
+ parser.exit()
335
+
336
+ args = parser.parse_args()
337
+
338
+ _ = mewc_to_md(mewc_input_folder=args.input_folder,
339
+ output_file=args.output_file,
340
+ mount_prefix=args.mount_prefix,
341
+ category_name_column=args.category_name_column)
342
+
343
+ if __name__ == '__main__':
344
+ main()