megadetector 5.0.11__py3-none-any.whl → 5.0.12__py3-none-any.whl

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

Potentially problematic release.


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

Files changed (201) hide show
  1. megadetector/api/__init__.py +0 -0
  2. megadetector/api/batch_processing/__init__.py +0 -0
  3. megadetector/api/batch_processing/api_core/__init__.py +0 -0
  4. megadetector/api/batch_processing/api_core/batch_service/__init__.py +0 -0
  5. megadetector/api/batch_processing/api_core/batch_service/score.py +439 -0
  6. megadetector/api/batch_processing/api_core/server.py +294 -0
  7. megadetector/api/batch_processing/api_core/server_api_config.py +98 -0
  8. megadetector/api/batch_processing/api_core/server_app_config.py +55 -0
  9. megadetector/api/batch_processing/api_core/server_batch_job_manager.py +220 -0
  10. megadetector/api/batch_processing/api_core/server_job_status_table.py +152 -0
  11. megadetector/api/batch_processing/api_core/server_orchestration.py +360 -0
  12. megadetector/api/batch_processing/api_core/server_utils.py +92 -0
  13. megadetector/api/batch_processing/api_core_support/__init__.py +0 -0
  14. megadetector/api/batch_processing/api_core_support/aggregate_results_manually.py +46 -0
  15. megadetector/api/batch_processing/api_support/__init__.py +0 -0
  16. megadetector/api/batch_processing/api_support/summarize_daily_activity.py +152 -0
  17. megadetector/api/batch_processing/data_preparation/__init__.py +0 -0
  18. megadetector/api/batch_processing/integration/digiKam/setup.py +6 -0
  19. megadetector/api/batch_processing/integration/digiKam/xmp_integration.py +465 -0
  20. megadetector/api/batch_processing/integration/eMammal/test_scripts/config_template.py +5 -0
  21. megadetector/api/batch_processing/integration/eMammal/test_scripts/push_annotations_to_emammal.py +126 -0
  22. megadetector/api/batch_processing/integration/eMammal/test_scripts/select_images_for_testing.py +55 -0
  23. megadetector/api/synchronous/__init__.py +0 -0
  24. megadetector/api/synchronous/api_core/animal_detection_api/__init__.py +0 -0
  25. megadetector/api/synchronous/api_core/animal_detection_api/api_backend.py +152 -0
  26. megadetector/api/synchronous/api_core/animal_detection_api/api_frontend.py +266 -0
  27. megadetector/api/synchronous/api_core/animal_detection_api/config.py +35 -0
  28. megadetector/api/synchronous/api_core/tests/__init__.py +0 -0
  29. megadetector/api/synchronous/api_core/tests/load_test.py +110 -0
  30. megadetector/classification/__init__.py +0 -0
  31. megadetector/classification/aggregate_classifier_probs.py +108 -0
  32. megadetector/classification/analyze_failed_images.py +227 -0
  33. megadetector/classification/cache_batchapi_outputs.py +198 -0
  34. megadetector/classification/create_classification_dataset.py +627 -0
  35. megadetector/classification/crop_detections.py +516 -0
  36. megadetector/classification/csv_to_json.py +226 -0
  37. megadetector/classification/detect_and_crop.py +855 -0
  38. megadetector/classification/efficientnet/__init__.py +9 -0
  39. megadetector/classification/efficientnet/model.py +415 -0
  40. megadetector/classification/efficientnet/utils.py +610 -0
  41. megadetector/classification/evaluate_model.py +520 -0
  42. megadetector/classification/identify_mislabeled_candidates.py +152 -0
  43. megadetector/classification/json_to_azcopy_list.py +63 -0
  44. megadetector/classification/json_validator.py +699 -0
  45. megadetector/classification/map_classification_categories.py +276 -0
  46. megadetector/classification/merge_classification_detection_output.py +506 -0
  47. megadetector/classification/prepare_classification_script.py +194 -0
  48. megadetector/classification/prepare_classification_script_mc.py +228 -0
  49. megadetector/classification/run_classifier.py +287 -0
  50. megadetector/classification/save_mislabeled.py +110 -0
  51. megadetector/classification/train_classifier.py +827 -0
  52. megadetector/classification/train_classifier_tf.py +725 -0
  53. megadetector/classification/train_utils.py +323 -0
  54. megadetector/data_management/__init__.py +0 -0
  55. megadetector/data_management/annotations/__init__.py +0 -0
  56. megadetector/data_management/annotations/annotation_constants.py +34 -0
  57. megadetector/data_management/camtrap_dp_to_coco.py +239 -0
  58. megadetector/data_management/cct_json_utils.py +395 -0
  59. megadetector/data_management/cct_to_md.py +176 -0
  60. megadetector/data_management/cct_to_wi.py +289 -0
  61. megadetector/data_management/coco_to_labelme.py +272 -0
  62. megadetector/data_management/coco_to_yolo.py +662 -0
  63. megadetector/data_management/databases/__init__.py +0 -0
  64. megadetector/data_management/databases/add_width_and_height_to_db.py +33 -0
  65. megadetector/data_management/databases/combine_coco_camera_traps_files.py +206 -0
  66. megadetector/data_management/databases/integrity_check_json_db.py +477 -0
  67. megadetector/data_management/databases/subset_json_db.py +115 -0
  68. megadetector/data_management/generate_crops_from_cct.py +149 -0
  69. megadetector/data_management/get_image_sizes.py +189 -0
  70. megadetector/data_management/importers/add_nacti_sizes.py +52 -0
  71. megadetector/data_management/importers/add_timestamps_to_icct.py +79 -0
  72. megadetector/data_management/importers/animl_results_to_md_results.py +158 -0
  73. megadetector/data_management/importers/auckland_doc_test_to_json.py +373 -0
  74. megadetector/data_management/importers/auckland_doc_to_json.py +201 -0
  75. megadetector/data_management/importers/awc_to_json.py +191 -0
  76. megadetector/data_management/importers/bellevue_to_json.py +273 -0
  77. megadetector/data_management/importers/cacophony-thermal-importer.py +796 -0
  78. megadetector/data_management/importers/carrizo_shrubfree_2018.py +269 -0
  79. megadetector/data_management/importers/carrizo_trail_cam_2017.py +289 -0
  80. megadetector/data_management/importers/cct_field_adjustments.py +58 -0
  81. megadetector/data_management/importers/channel_islands_to_cct.py +913 -0
  82. megadetector/data_management/importers/eMammal/copy_and_unzip_emammal.py +180 -0
  83. megadetector/data_management/importers/eMammal/eMammal_helpers.py +249 -0
  84. megadetector/data_management/importers/eMammal/make_eMammal_json.py +223 -0
  85. megadetector/data_management/importers/ena24_to_json.py +276 -0
  86. megadetector/data_management/importers/filenames_to_json.py +386 -0
  87. megadetector/data_management/importers/helena_to_cct.py +283 -0
  88. megadetector/data_management/importers/idaho-camera-traps.py +1407 -0
  89. megadetector/data_management/importers/idfg_iwildcam_lila_prep.py +294 -0
  90. megadetector/data_management/importers/jb_csv_to_json.py +150 -0
  91. megadetector/data_management/importers/mcgill_to_json.py +250 -0
  92. megadetector/data_management/importers/missouri_to_json.py +490 -0
  93. megadetector/data_management/importers/nacti_fieldname_adjustments.py +79 -0
  94. megadetector/data_management/importers/noaa_seals_2019.py +181 -0
  95. megadetector/data_management/importers/pc_to_json.py +365 -0
  96. megadetector/data_management/importers/plot_wni_giraffes.py +123 -0
  97. megadetector/data_management/importers/prepare-noaa-fish-data-for-lila.py +359 -0
  98. megadetector/data_management/importers/prepare_zsl_imerit.py +131 -0
  99. megadetector/data_management/importers/rspb_to_json.py +356 -0
  100. megadetector/data_management/importers/save_the_elephants_survey_A.py +320 -0
  101. megadetector/data_management/importers/save_the_elephants_survey_B.py +329 -0
  102. megadetector/data_management/importers/snapshot_safari_importer.py +758 -0
  103. megadetector/data_management/importers/snapshot_safari_importer_reprise.py +665 -0
  104. megadetector/data_management/importers/snapshot_serengeti_lila.py +1067 -0
  105. megadetector/data_management/importers/snapshotserengeti/make_full_SS_json.py +150 -0
  106. megadetector/data_management/importers/snapshotserengeti/make_per_season_SS_json.py +153 -0
  107. megadetector/data_management/importers/sulross_get_exif.py +65 -0
  108. megadetector/data_management/importers/timelapse_csv_set_to_json.py +490 -0
  109. megadetector/data_management/importers/ubc_to_json.py +399 -0
  110. megadetector/data_management/importers/umn_to_json.py +507 -0
  111. megadetector/data_management/importers/wellington_to_json.py +263 -0
  112. megadetector/data_management/importers/wi_to_json.py +442 -0
  113. megadetector/data_management/importers/zamba_results_to_md_results.py +181 -0
  114. megadetector/data_management/labelme_to_coco.py +547 -0
  115. megadetector/data_management/labelme_to_yolo.py +272 -0
  116. megadetector/data_management/lila/__init__.py +0 -0
  117. megadetector/data_management/lila/add_locations_to_island_camera_traps.py +97 -0
  118. megadetector/data_management/lila/add_locations_to_nacti.py +147 -0
  119. megadetector/data_management/lila/create_lila_blank_set.py +558 -0
  120. megadetector/data_management/lila/create_lila_test_set.py +152 -0
  121. megadetector/data_management/lila/create_links_to_md_results_files.py +106 -0
  122. megadetector/data_management/lila/download_lila_subset.py +178 -0
  123. megadetector/data_management/lila/generate_lila_per_image_labels.py +516 -0
  124. megadetector/data_management/lila/get_lila_annotation_counts.py +170 -0
  125. megadetector/data_management/lila/get_lila_image_counts.py +112 -0
  126. megadetector/data_management/lila/lila_common.py +300 -0
  127. megadetector/data_management/lila/test_lila_metadata_urls.py +132 -0
  128. megadetector/data_management/ocr_tools.py +874 -0
  129. megadetector/data_management/read_exif.py +681 -0
  130. megadetector/data_management/remap_coco_categories.py +84 -0
  131. megadetector/data_management/remove_exif.py +66 -0
  132. megadetector/data_management/resize_coco_dataset.py +189 -0
  133. megadetector/data_management/wi_download_csv_to_coco.py +246 -0
  134. megadetector/data_management/yolo_output_to_md_output.py +441 -0
  135. megadetector/data_management/yolo_to_coco.py +676 -0
  136. megadetector/detection/__init__.py +0 -0
  137. megadetector/detection/detector_training/__init__.py +0 -0
  138. megadetector/detection/detector_training/model_main_tf2.py +114 -0
  139. megadetector/detection/process_video.py +702 -0
  140. megadetector/detection/pytorch_detector.py +341 -0
  141. megadetector/detection/run_detector.py +779 -0
  142. megadetector/detection/run_detector_batch.py +1219 -0
  143. megadetector/detection/run_inference_with_yolov5_val.py +917 -0
  144. megadetector/detection/run_tiled_inference.py +934 -0
  145. megadetector/detection/tf_detector.py +189 -0
  146. megadetector/detection/video_utils.py +606 -0
  147. megadetector/postprocessing/__init__.py +0 -0
  148. megadetector/postprocessing/add_max_conf.py +64 -0
  149. megadetector/postprocessing/categorize_detections_by_size.py +163 -0
  150. megadetector/postprocessing/combine_api_outputs.py +249 -0
  151. megadetector/postprocessing/compare_batch_results.py +958 -0
  152. megadetector/postprocessing/convert_output_format.py +396 -0
  153. megadetector/postprocessing/load_api_results.py +195 -0
  154. megadetector/postprocessing/md_to_coco.py +310 -0
  155. megadetector/postprocessing/md_to_labelme.py +330 -0
  156. megadetector/postprocessing/merge_detections.py +401 -0
  157. megadetector/postprocessing/postprocess_batch_results.py +1902 -0
  158. megadetector/postprocessing/remap_detection_categories.py +170 -0
  159. megadetector/postprocessing/render_detection_confusion_matrix.py +660 -0
  160. megadetector/postprocessing/repeat_detection_elimination/find_repeat_detections.py +211 -0
  161. megadetector/postprocessing/repeat_detection_elimination/remove_repeat_detections.py +83 -0
  162. megadetector/postprocessing/repeat_detection_elimination/repeat_detections_core.py +1631 -0
  163. megadetector/postprocessing/separate_detections_into_folders.py +730 -0
  164. megadetector/postprocessing/subset_json_detector_output.py +696 -0
  165. megadetector/postprocessing/top_folders_to_bottom.py +223 -0
  166. megadetector/taxonomy_mapping/__init__.py +0 -0
  167. megadetector/taxonomy_mapping/map_lila_taxonomy_to_wi_taxonomy.py +491 -0
  168. megadetector/taxonomy_mapping/map_new_lila_datasets.py +150 -0
  169. megadetector/taxonomy_mapping/prepare_lila_taxonomy_release.py +142 -0
  170. megadetector/taxonomy_mapping/preview_lila_taxonomy.py +590 -0
  171. megadetector/taxonomy_mapping/retrieve_sample_image.py +71 -0
  172. megadetector/taxonomy_mapping/simple_image_download.py +219 -0
  173. megadetector/taxonomy_mapping/species_lookup.py +834 -0
  174. megadetector/taxonomy_mapping/taxonomy_csv_checker.py +159 -0
  175. megadetector/taxonomy_mapping/taxonomy_graph.py +346 -0
  176. megadetector/taxonomy_mapping/validate_lila_category_mappings.py +83 -0
  177. megadetector/utils/__init__.py +0 -0
  178. megadetector/utils/azure_utils.py +178 -0
  179. megadetector/utils/ct_utils.py +612 -0
  180. megadetector/utils/directory_listing.py +246 -0
  181. megadetector/utils/md_tests.py +968 -0
  182. megadetector/utils/path_utils.py +1044 -0
  183. megadetector/utils/process_utils.py +157 -0
  184. megadetector/utils/sas_blob_utils.py +509 -0
  185. megadetector/utils/split_locations_into_train_val.py +228 -0
  186. megadetector/utils/string_utils.py +92 -0
  187. megadetector/utils/url_utils.py +323 -0
  188. megadetector/utils/write_html_image_list.py +225 -0
  189. megadetector/visualization/__init__.py +0 -0
  190. megadetector/visualization/plot_utils.py +293 -0
  191. megadetector/visualization/render_images_with_thumbnails.py +275 -0
  192. megadetector/visualization/visualization_utils.py +1536 -0
  193. megadetector/visualization/visualize_db.py +550 -0
  194. megadetector/visualization/visualize_detector_output.py +405 -0
  195. {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/METADATA +1 -1
  196. megadetector-5.0.12.dist-info/RECORD +199 -0
  197. megadetector-5.0.12.dist-info/top_level.txt +1 -0
  198. megadetector-5.0.11.dist-info/RECORD +0 -5
  199. megadetector-5.0.11.dist-info/top_level.txt +0 -1
  200. {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/LICENSE +0 -0
  201. {megadetector-5.0.11.dist-info → megadetector-5.0.12.dist-info}/WHEEL +0 -0
@@ -0,0 +1,1902 @@
1
+ """
2
+
3
+ postprocess_batch_results.py
4
+
5
+ Given a .json or .csv file containing MD results, do one or more of the following:
6
+
7
+ * Sample detections/non-detections and render to HTML (when ground truth isn't
8
+ available) (this is 99.9% of what this module is for)
9
+ * Evaluate detector precision/recall, optionally rendering results (requires
10
+ ground truth)
11
+ * Sample true/false positives/negatives and render to HTML (requires ground
12
+ truth)
13
+
14
+ Ground truth, if available, must be in COCO Camera Traps format:
15
+
16
+ https://github.com/agentmorris/MegaDetector/blob/main/megadetector/data_management/README.md#coco-camera-traps-format
17
+
18
+ """
19
+
20
+ #%% Constants and imports
21
+
22
+ import argparse
23
+ import collections
24
+ import copy
25
+ import errno
26
+ import io
27
+ import os
28
+ import sys
29
+ import time
30
+ import uuid
31
+ import warnings
32
+ import random
33
+
34
+ from enum import IntEnum
35
+ from multiprocessing.pool import ThreadPool
36
+ from multiprocessing.pool import Pool
37
+ from functools import partial
38
+
39
+ import matplotlib.pyplot as plt
40
+ import numpy as np
41
+ import humanfriendly
42
+ import pandas as pd
43
+
44
+ from sklearn.metrics import precision_recall_curve, confusion_matrix, average_precision_score
45
+ from tqdm import tqdm
46
+
47
+ from megadetector.visualization import visualization_utils as vis_utils
48
+ from megadetector.visualization import plot_utils
49
+ from megadetector.utils.write_html_image_list import write_html_image_list
50
+ from megadetector.utils import path_utils
51
+ from megadetector.utils.ct_utils import args_to_object, sets_overlap
52
+ from megadetector.data_management.cct_json_utils import (CameraTrapJsonUtils, IndexedJsonDb)
53
+ from megadetector.postprocessing.load_api_results import load_api_results
54
+ from megadetector.detection.run_detector import get_typical_confidence_threshold_from_results
55
+
56
+ warnings.filterwarnings('ignore', '(Possibly )?corrupt EXIF data', UserWarning)
57
+
58
+
59
+ #%% Options
60
+
61
+ DEFAULT_NEGATIVE_CLASSES = ['empty']
62
+ DEFAULT_UNKNOWN_CLASSES = ['unknown', 'unlabeled', 'ambiguous']
63
+
64
+ # Make sure there is no overlap between the two sets, because this will cause
65
+ # issues in the code
66
+ assert not sets_overlap(DEFAULT_NEGATIVE_CLASSES, DEFAULT_UNKNOWN_CLASSES), (
67
+ 'Default negative and unknown classes cannot overlap.')
68
+
69
+
70
+ class PostProcessingOptions:
71
+ """
72
+ Options used to parameterize process_batch_results().
73
+ """
74
+
75
+ ### Required inputs
76
+
77
+ #: MD results .json file to process
78
+ md_results_file = ''
79
+
80
+ #: Folder to which we should write HTML output
81
+ output_dir = ''
82
+
83
+ ### Options
84
+
85
+ #: Folder where images live (filenames in [md_results_file] should be relative to this folder)
86
+ image_base_dir = '.'
87
+
88
+ ## These apply only when we're doing ground-truth comparisons
89
+
90
+ #: Optional .json file containing ground truth information
91
+ ground_truth_json_file = ''
92
+
93
+ #: Classes we'll treat as negative
94
+ #:
95
+ #: Include the token "#NO_LABELS#" to indicate that an image with no annotations
96
+ #: should be considered empty.
97
+ negative_classes = DEFAULT_NEGATIVE_CLASSES
98
+
99
+ #: Classes we'll treat as neither positive nor negative
100
+ unlabeled_classes = DEFAULT_UNKNOWN_CLASSES
101
+
102
+ #: A list of output sets that we should count, but not render images for.
103
+ #:
104
+ #: Typically used to preview sets with lots of empties, where you don't want to
105
+ #: subset but also don't want to render 100,000 empty images.
106
+ #:
107
+ #: detections, non_detections
108
+ #: detections_animal, detections_person, detections_vehicle
109
+ rendering_bypass_sets = []
110
+
111
+ #: If this is None, choose a confidence threshold based on the detector version.
112
+ #:
113
+ #: This can either be a float or a dictionary mapping category names (not IDs) to
114
+ #: thresholds. The category "default" can be used to specify thresholds for
115
+ #: other categories. Currently the use of a dict here is not supported when
116
+ #: ground truth is supplied.
117
+ confidence_threshold = None
118
+
119
+ #: Confidence threshold to apply to classification (not detection) results
120
+ #:
121
+ #: Only a float is supported here (unlike the "confidence_threshold" parameter, which
122
+ #: can be a dict).
123
+ classification_confidence_threshold = 0.5
124
+
125
+ #: Used for summary statistics only
126
+ target_recall = 0.9
127
+
128
+ #: Number of images to sample, -1 for "all images"
129
+ num_images_to_sample = 500
130
+
131
+ #: Random seed for sampling, or None
132
+ sample_seed = 0 # None
133
+
134
+ #: Image width for images in the HTML output
135
+ viz_target_width = 800
136
+
137
+ #: Line width (in pixels) for rendering detections
138
+ line_thickness = 4
139
+
140
+ #: Box expansion (in pixels) for rendering detections
141
+ box_expansion = 0
142
+
143
+ #: Job name to include in big letters in the output HTML
144
+ job_name_string = None
145
+
146
+ #: Model version string to include in the output HTML
147
+ model_version_string = None
148
+
149
+ #: Sort order for the output, should be one of "filename", "confidence", or "random"
150
+ html_sort_order = 'filename'
151
+
152
+ #: If True, images in the output HTML will be links back to the original images
153
+ link_images_to_originals = True
154
+
155
+ #: Optionally separate detections into categories (animal/vehicle/human)
156
+ #:
157
+ #: Currently only supported when ground truth is unavailable
158
+ separate_detections_by_category = True
159
+
160
+ #: Optionally replace one or more strings in filenames with other strings;
161
+ #: useful for taking a set of results generated for one folder structure
162
+ #: and applying them to a slightly different folder structure.
163
+ api_output_filename_replacements = {}
164
+
165
+ #: Optionally replace one or more strings in filenames with other strings;
166
+ #: useful for taking a set of results generated for one folder structure
167
+ #: and applying them to a slightly different folder structure.
168
+ ground_truth_filename_replacements = {}
169
+
170
+ #: Allow bypassing API output loading when operating on previously-loaded
171
+ #: results. If present, this is a Pandas DataFrame. Almost never useful.
172
+ api_detection_results = None
173
+
174
+ #: Allow bypassing API output loading when operating on previously-loaded
175
+ #: results. If present, this is a str --> obj dict. Almost never useful.
176
+ api_other_fields = None
177
+
178
+ #: Should we also split out a separate report about the detections that were
179
+ #: just below our main confidence threshold?
180
+ #:
181
+ #: Currently only supported when ground truth is unavailable.
182
+ include_almost_detections = False
183
+
184
+ #: Only a float is supported here (unlike the "confidence_threshold" parameter, which
185
+ #: can be a dict).
186
+ almost_detection_confidence_threshold = None
187
+
188
+ #: Enable/disable rendering parallelization
189
+ parallelize_rendering = False
190
+
191
+ #: Number of threads/processes to use for rendering parallelization
192
+ parallelize_rendering_n_cores = 25
193
+
194
+ #: Whether to use threads (True) or processes (False) for rendering parallelization
195
+ parallelize_rendering_with_threads = True
196
+
197
+ #: When classification results are present, should be sort alphabetically by class name (False)
198
+ #: or in descending order by frequency (True)?
199
+ sort_classification_results_by_count = False
200
+
201
+ #: Should we split individual pages up into smaller pages if there are more than
202
+ #: N images?
203
+ max_figures_per_html_file = None
204
+
205
+ # ...PostProcessingOptions
206
+
207
+
208
+ class PostProcessingResults:
209
+ """
210
+ Return format from process_batch_results
211
+ """
212
+
213
+ #: HTML file to which preview information was written
214
+ output_html_file = ''
215
+
216
+ #: Pandas Dataframe containing detection results
217
+ api_detection_results = None
218
+
219
+ #: str --> obj dictionary containing other information loaded from the results file
220
+ api_other_fields = None
221
+
222
+
223
+ ##%% Helper classes and functions
224
+
225
+ class DetectionStatus(IntEnum):
226
+ """
227
+ Flags used to mark images as positive or negative for P/R analysis
228
+ (according to ground truth and/or detector output)
229
+
230
+ :meta private:
231
+ """
232
+
233
+ DS_NEGATIVE = 0
234
+ DS_POSITIVE = 1
235
+
236
+ # Anything greater than this isn't clearly positive or negative
237
+ DS_MAX_DEFINITIVE_VALUE = DS_POSITIVE
238
+
239
+ # image has annotations suggesting both negative and positive
240
+ DS_AMBIGUOUS = 2
241
+
242
+ # image is not annotated or is annotated with 'unknown', 'unlabeled', ETC.
243
+ DS_UNKNOWN = 3
244
+
245
+ # image has not yet been assigned a state
246
+ DS_UNASSIGNED = 4
247
+
248
+ # In some analyses, we add an additional class that lets us look at
249
+ # detections just below our main confidence threshold
250
+ DS_ALMOST = 5
251
+
252
+
253
+ def _mark_detection_status(indexed_db,
254
+ negative_classes=DEFAULT_NEGATIVE_CLASSES,
255
+ unknown_classes=DEFAULT_UNKNOWN_CLASSES):
256
+ """
257
+ For each image in indexed_db.db['images'], add a '_detection_status' field
258
+ to indicate whether to treat this image as positive, negative, ambiguous,
259
+ or unknown.
260
+
261
+ Makes modifications in-place.
262
+
263
+ returns (n_negative, n_positive, n_unknown, n_ambiguous)
264
+ """
265
+
266
+ negative_classes = set(negative_classes)
267
+ unknown_classes = set(unknown_classes)
268
+
269
+ # count the # of images with each type of DetectionStatus
270
+ n_unknown = 0
271
+ n_ambiguous = 0
272
+ n_positive = 0
273
+ n_negative = 0
274
+
275
+ print('Preparing ground-truth annotations')
276
+ for im in tqdm(indexed_db.db['images']):
277
+
278
+ image_id = im['id']
279
+ annotations = indexed_db.image_id_to_annotations[image_id]
280
+ categories = [ann['category_id'] for ann in annotations]
281
+ category_names = set(indexed_db.cat_id_to_name[cat] for cat in categories)
282
+
283
+ # Check whether this image has:
284
+ # - unknown / unassigned-type labels
285
+ # - negative-type labels
286
+ # - positive labels (i.e., labels that are neither unknown nor negative)
287
+ has_unknown_labels = sets_overlap(category_names, unknown_classes)
288
+ has_negative_labels = sets_overlap(category_names, negative_classes)
289
+ has_positive_labels = 0 < len(category_names - (unknown_classes | negative_classes))
290
+ # assert has_unknown_labels is False, '{} has unknown labels'.format(annotations)
291
+
292
+ # If there are no image annotations...
293
+ if len(categories) == 0:
294
+
295
+ if '#NO_LABELS#' in negative_classes:
296
+ n_negative += 1
297
+ im['_detection_status'] = DetectionStatus.DS_NEGATIVE
298
+ else:
299
+ n_unknown += 1
300
+ im['_detection_status'] = DetectionStatus.DS_UNKNOWN
301
+
302
+ # n_negative += 1
303
+ # im['_detection_status'] = DetectionStatus.DS_NEGATIVE
304
+
305
+ # If the image has more than one type of labels, it's ambiguous
306
+ # note: bools are automatically converted to 0/1, so we can sum
307
+ elif (has_unknown_labels + has_negative_labels + has_positive_labels) > 1:
308
+ n_ambiguous += 1
309
+ im['_detection_status'] = DetectionStatus.DS_AMBIGUOUS
310
+
311
+ # After the check above, we can be sure it's only one of positive,
312
+ # negative, or unknown.
313
+ #
314
+ # Important: do not merge the following 'unknown' branch with the first
315
+ # 'unknown' branch above, where we tested 'if len(categories) == 0'
316
+ #
317
+ # If the image has only unknown labels
318
+ elif has_unknown_labels:
319
+ n_unknown += 1
320
+ im['_detection_status'] = DetectionStatus.DS_UNKNOWN
321
+
322
+ # If the image has only negative labels
323
+ elif has_negative_labels:
324
+ n_negative += 1
325
+ im['_detection_status'] = DetectionStatus.DS_NEGATIVE
326
+
327
+ # If the images has only positive labels
328
+ elif has_positive_labels:
329
+ n_positive += 1
330
+ im['_detection_status'] = DetectionStatus.DS_POSITIVE
331
+
332
+ # Annotate the category, if it is unambiguous
333
+ if len(category_names) == 1:
334
+ im['_unambiguous_category'] = list(category_names)[0]
335
+
336
+ else:
337
+ raise Exception('Invalid detection state')
338
+
339
+ # ...for each image
340
+
341
+ return n_negative, n_positive, n_unknown, n_ambiguous
342
+
343
+ # ..._mark_detection_status()
344
+
345
+
346
+ def is_sas_url(s) -> bool:
347
+ """
348
+ Placeholder for a more robust way to verify that a link is a SAS URL.
349
+ 99.999% of the time this will suffice for what we're using it for right now.
350
+
351
+ :meta private:
352
+ """
353
+
354
+ return (s.startswith(('http://', 'https://')) and ('core.windows.net' in s)
355
+ and ('?' in s))
356
+
357
+
358
+ def relative_sas_url(folder_url, relative_path):
359
+ """
360
+ Given a container-level or folder-level SAS URL, create a SAS URL to the
361
+ specified relative path.
362
+
363
+ :meta private:
364
+ """
365
+
366
+ relative_path = relative_path.replace('%','%25')
367
+ relative_path = relative_path.replace('#','%23')
368
+ relative_path = relative_path.replace(' ','%20')
369
+
370
+ if not is_sas_url(folder_url):
371
+ return None
372
+ tokens = folder_url.split('?')
373
+ assert len(tokens) == 2
374
+ if not tokens[0].endswith('/'):
375
+ tokens[0] = tokens[0] + '/'
376
+ if relative_path.startswith('/'):
377
+ relative_path = relative_path[1:]
378
+ return tokens[0] + relative_path + '?' + tokens[1]
379
+
380
+
381
+ def _render_bounding_boxes(
382
+ image_base_dir,
383
+ image_relative_path,
384
+ display_name,
385
+ detections,
386
+ res,
387
+ ground_truth_boxes=None,
388
+ detection_categories=None,
389
+ classification_categories=None,
390
+ options=None):
391
+ """
392
+ Renders detection bounding boxes on a single image.
393
+
394
+ This is an internal function; if you want tools for rendering boxes on images, see
395
+ visualization.visualization_utils.
396
+
397
+ The source image is:
398
+
399
+ image_base_dir / image_relative_path
400
+
401
+ The target image is, for example:
402
+
403
+ [options.output_dir] /
404
+ ['detections' or 'non_detections'] /
405
+ [filename with slashes turned into tildes]
406
+
407
+ "res" is a result type, e.g. "detections", "non-detections"; this determines the
408
+ output folder for the rendered image.
409
+
410
+ Only very preliminary support is provided for ground truth box rendering.
411
+
412
+ Returns the html info struct for this image in the format that's used for
413
+ write_html_image_list.
414
+
415
+ :meta private:
416
+ """
417
+
418
+ if options is None:
419
+ options = PostProcessingOptions()
420
+
421
+ # Leaving code in place for reading from blob storage, may support this
422
+ # in the future.
423
+ """
424
+ stream = io.BytesIO()
425
+ _ = blob_service.get_blob_to_stream(container_name, image_id, stream)
426
+ # resize is to display them in this notebook or in the HTML more quickly
427
+ image = Image.open(stream).resize(viz_size)
428
+ """
429
+
430
+ image_full_path = None
431
+
432
+ if res in options.rendering_bypass_sets:
433
+
434
+ sample_name = res + '_' + path_utils.flatten_path(image_relative_path)
435
+
436
+ else:
437
+
438
+ if is_sas_url(image_base_dir):
439
+ image_full_path = relative_sas_url(image_base_dir, image_relative_path)
440
+ else:
441
+ image_full_path = os.path.join(image_base_dir, image_relative_path)
442
+
443
+ # os.path.isfile() is slow when mounting remote directories; much faster
444
+ # to just try/except on the image open.
445
+ try:
446
+ image = vis_utils.open_image(image_full_path)
447
+ except:
448
+ print('Warning: could not open image file {}'.format(image_full_path))
449
+ image = None
450
+ # return ''
451
+
452
+ # Render images to a flat folder
453
+ sample_name = res + '_' + path_utils.flatten_path(image_relative_path)
454
+ fullpath = os.path.join(options.output_dir, res, sample_name)
455
+
456
+ if image is not None:
457
+
458
+ original_size = image.size
459
+
460
+ if options.viz_target_width is not None:
461
+ image = vis_utils.resize_image(image, options.viz_target_width)
462
+
463
+ if ground_truth_boxes is not None and len(ground_truth_boxes) > 0:
464
+
465
+ # Create class labels like "gt_1" or "gt_27"
466
+ gt_classes = [0] * len(ground_truth_boxes)
467
+ label_map = {0:'ground truth'}
468
+ # for i_box,box in enumerate(ground_truth_boxes):
469
+ # gt_classes.append('_' + str(box[-1]))
470
+ vis_utils.render_db_bounding_boxes(ground_truth_boxes, gt_classes, image,
471
+ original_size=original_size,label_map=label_map,
472
+ thickness=4,expansion=4)
473
+
474
+ # render_detection_bounding_boxes expects either a float or a dict mapping
475
+ # category IDs to names.
476
+ if isinstance(options.confidence_threshold,float):
477
+ rendering_confidence_threshold = options.confidence_threshold
478
+ else:
479
+ category_ids = set()
480
+ for d in detections:
481
+ category_ids.add(d['category'])
482
+ rendering_confidence_threshold = {}
483
+ for category_id in category_ids:
484
+ rendering_confidence_threshold[category_id] = \
485
+ _get_threshold_for_category_id(category_id, options, detection_categories)
486
+
487
+ vis_utils.render_detection_bounding_boxes(
488
+ detections, image,
489
+ label_map=detection_categories,
490
+ classification_label_map=classification_categories,
491
+ confidence_threshold=rendering_confidence_threshold,
492
+ thickness=options.line_thickness,
493
+ expansion=options.box_expansion)
494
+
495
+ try:
496
+ image.save(fullpath)
497
+ except OSError as e:
498
+ # errno.ENAMETOOLONG doesn't get thrown properly on Windows, so
499
+ # we awkwardly check against a hard-coded limit
500
+ if (e.errno == errno.ENAMETOOLONG) or (len(fullpath) >= 259):
501
+ extension = os.path.splitext(sample_name)[1]
502
+ sample_name = res + '_' + str(uuid.uuid4()) + extension
503
+ image.save(os.path.join(options.output_dir, res, sample_name))
504
+ else:
505
+ raise
506
+
507
+ # Use slashes regardless of os
508
+ file_name = '{}/{}'.format(res,sample_name)
509
+
510
+ info = {
511
+ 'filename': file_name,
512
+ 'title': display_name,
513
+ 'textStyle':\
514
+ 'font-family:verdana,arial,calibri;font-size:80%;text-align:left;margin-top:20;margin-bottom:5'
515
+ }
516
+
517
+ # Optionally add links back to the original images
518
+ if options.link_images_to_originals and (image_full_path is not None):
519
+
520
+ # Handling special characters in links has been pushed down into
521
+ # write_html_image_list
522
+ #
523
+ # link_target = image_full_path.replace('\\','/')
524
+ # link_target = urllib.parse.quote(link_target)
525
+ link_target = image_full_path
526
+ info['linkTarget'] = link_target
527
+
528
+ return info
529
+
530
+ # ..._render_bounding_boxes
531
+
532
+
533
+ def _prepare_html_subpages(images_html, output_dir, options=None):
534
+ """
535
+ Write out a series of html image lists, e.g. the "detections" or "non-detections"
536
+ pages.
537
+
538
+ image_html is a dictionary mapping an html page name (e.g. "detections_animal") to
539
+ a list of image structs friendly to write_html_image_list.
540
+
541
+ Returns a dictionary mapping category names to image counts.
542
+ """
543
+
544
+ if options is None:
545
+ options = PostProcessingOptions()
546
+
547
+ # Count items in each category
548
+ image_counts = {}
549
+ for res, array in images_html.items():
550
+ image_counts[res] = len(array)
551
+
552
+ # Optionally sort by filename before writing to html
553
+ if options.html_sort_order == 'filename':
554
+ images_html_sorted = {}
555
+ for res, array in images_html.items():
556
+ sorted_array = sorted(array, key=lambda x: x['filename'])
557
+ images_html_sorted[res] = sorted_array
558
+ images_html = images_html_sorted
559
+
560
+ # Optionally sort by confidence before writing to html
561
+ elif options.html_sort_order == 'confidence':
562
+ images_html_sorted = {}
563
+ for res, array in images_html.items():
564
+
565
+ if not all(['max_conf' in d for d in array]):
566
+ print("Warning: some elements in the {} page don't have confidence values, can't sort by confidence".format(res))
567
+ else:
568
+ sorted_array = sorted(array, key=lambda x: x['max_conf'], reverse=True)
569
+ images_html_sorted[res] = sorted_array
570
+ images_html = images_html_sorted
571
+
572
+ else:
573
+ assert options.html_sort_order == 'random',\
574
+ 'Unrecognized sort order {}'.format(options.html_sort_order)
575
+ images_html_sorted = {}
576
+ for res, array in images_html.items():
577
+ sorted_array = random.sample(array,len(array))
578
+ images_html_sorted[res] = sorted_array
579
+ images_html = images_html_sorted
580
+
581
+ # Write the individual HTML files
582
+ for res, array in images_html.items():
583
+
584
+ html_image_list_options = {}
585
+ html_image_list_options['maxFiguresPerHtmlFile'] = options.max_figures_per_html_file
586
+ html_image_list_options['headerHtml'] = '<h1>{}</h1>'.format(res.upper())
587
+
588
+ # Don't write empty pages
589
+ if len(array) == 0:
590
+ continue
591
+ else:
592
+ write_html_image_list(
593
+ filename=os.path.join(output_dir, '{}.html'.format(res)),
594
+ images=array,
595
+ options=html_image_list_options)
596
+
597
+ return image_counts
598
+
599
+ # ..._prepare_html_subpages()
600
+
601
+
602
+ def _get_threshold_for_category_name(category_name,options):
603
+ """
604
+ Determines the confidence threshold we should use for a specific category name.
605
+ """
606
+
607
+ if isinstance(options.confidence_threshold,float):
608
+ return options.confidence_threshold
609
+ else:
610
+ assert isinstance(options.confidence_threshold,dict), \
611
+ 'confidence_threshold must either be a float or a dict'
612
+
613
+ if category_name in options.confidence_threshold:
614
+
615
+ return options.confidence_threshold[category_name]
616
+
617
+ else:
618
+ assert 'default' in options.confidence_threshold, \
619
+ 'category {} not in confidence_threshold dict, and no default supplied'.format(
620
+ category_name)
621
+ return options.confidence_threshold['default']
622
+
623
+
624
+ def _get_threshold_for_category_id(category_id,options,detection_categories):
625
+ """
626
+ Determines the confidence threshold we should use for a specific category ID.
627
+
628
+ [detection_categories] is a dict mapping category IDs to names.
629
+ """
630
+
631
+ if isinstance(options.confidence_threshold,float):
632
+ return options.confidence_threshold
633
+
634
+ assert category_id in detection_categories, \
635
+ 'Invalid category ID {}'.format(category_id)
636
+
637
+ category_name = detection_categories[category_id]
638
+
639
+ return _get_threshold_for_category_name(category_name,options)
640
+
641
+
642
+ def _get_positive_categories(detections,options,detection_categories):
643
+ """
644
+ Gets a sorted list of unique categories (as string IDs) above the threshold for this image
645
+
646
+ [detection_categories] is a dict mapping category IDs to names.
647
+ """
648
+
649
+ positive_categories = set()
650
+ for d in detections:
651
+ threshold = _get_threshold_for_category_id(d['category'], options, detection_categories)
652
+ if d['conf'] >= threshold:
653
+ positive_categories.add(d['category'])
654
+ return sorted(positive_categories)
655
+
656
+
657
+ def _has_positive_detection(detections,options,detection_categories):
658
+ """
659
+ Determines whether any positive detections are present in the detection list
660
+ [detections].
661
+ """
662
+
663
+ found_positive_detection = False
664
+ for d in detections:
665
+ threshold = _get_threshold_for_category_id(d['category'], options, detection_categories)
666
+ if d['conf'] >= threshold:
667
+ found_positive_detection = True
668
+ break
669
+ return found_positive_detection
670
+
671
+
672
+ def _render_image_no_gt(file_info,detection_categories_to_results_name,
673
+ detection_categories,classification_categories,
674
+ options):
675
+ """
676
+ Renders an image (with no ground truth information)
677
+
678
+ Returns a list of rendering structs, where the first item is a category (e.g. "detections_animal"),
679
+ and the second is a dict of information needed for rendering. E.g.:
680
+
681
+ [['detections_animal',
682
+ {
683
+ 'filename': 'detections_animal/detections_animal_blah~01060415.JPG',
684
+ 'title': '<b>Result type</b>: detections_animal,
685
+ <b>Image</b>: blah\\01060415.JPG,
686
+ <b>Max conf</b>: 0.897',
687
+ 'textStyle': 'font-family:verdana,arial,calibri;font-size:80%;text-align:left;margin-top:20;margin-bottom:5',
688
+ 'linkTarget': 'full_path_to_%5C01060415.JPG'
689
+ }]]
690
+
691
+ When no classification data is present, this list will always be length-1. When
692
+ classification data is present, an image may appear in multiple categories.
693
+
694
+ Populates the 'max_conf' field of the first element of the list.
695
+
696
+ Returns None if there are any errors.
697
+ """
698
+
699
+ image_relative_path = file_info[0]
700
+ max_conf = file_info[1]
701
+ detections = file_info[2]
702
+
703
+ # Determine whether any positive detections are present (using a threshold that
704
+ # may vary by category)
705
+ found_positive_detection = _has_positive_detection(detections,options,detection_categories)
706
+
707
+ detection_status = DetectionStatus.DS_UNASSIGNED
708
+ if found_positive_detection:
709
+ detection_status = DetectionStatus.DS_POSITIVE
710
+ else:
711
+ if options.include_almost_detections:
712
+ if max_conf >= options.almost_detection_confidence_threshold:
713
+ detection_status = DetectionStatus.DS_ALMOST
714
+ else:
715
+ detection_status = DetectionStatus.DS_NEGATIVE
716
+ else:
717
+ detection_status = DetectionStatus.DS_NEGATIVE
718
+
719
+ if detection_status == DetectionStatus.DS_POSITIVE:
720
+ if options.separate_detections_by_category:
721
+ positive_categories = tuple(_get_positive_categories(detections,options,detection_categories))
722
+ if positive_categories not in detection_categories_to_results_name:
723
+ raise ValueError('Error: {} not in category mapping (file {})'.format(
724
+ str(positive_categories),image_relative_path))
725
+ res = detection_categories_to_results_name[positive_categories]
726
+ else:
727
+ res = 'detections'
728
+
729
+ elif detection_status == DetectionStatus.DS_NEGATIVE:
730
+ res = 'non_detections'
731
+ else:
732
+ assert detection_status == DetectionStatus.DS_ALMOST
733
+ res = 'almost_detections'
734
+
735
+ display_name = '<b>Result type</b>: {}, <b>Image</b>: {}, <b>Max conf</b>: {:0.3f}'.format(
736
+ res, image_relative_path, max_conf)
737
+
738
+ rendering_options = copy.copy(options)
739
+ if detection_status == DetectionStatus.DS_ALMOST:
740
+ rendering_options.confidence_threshold = \
741
+ rendering_options.almost_detection_confidence_threshold
742
+
743
+ rendered_image_html_info = _render_bounding_boxes(
744
+ image_base_dir=options.image_base_dir,
745
+ image_relative_path=image_relative_path,
746
+ display_name=display_name,
747
+ detections=detections,
748
+ res=res,
749
+ ground_truth_boxes=None,
750
+ detection_categories=detection_categories,
751
+ classification_categories=classification_categories,
752
+ options=rendering_options)
753
+
754
+ image_result = None
755
+
756
+ if len(rendered_image_html_info) > 0:
757
+
758
+ image_result = [[res, rendered_image_html_info]]
759
+
760
+ max_conf = 0
761
+
762
+ for det in detections:
763
+
764
+ if det['conf'] > max_conf:
765
+ max_conf = det['conf']
766
+
767
+ if ('classifications' in det):
768
+
769
+ # This is a list of [class,confidence] pairs, sorted by confidence
770
+ classifications = det['classifications']
771
+ top1_class_id = classifications[0][0]
772
+ top1_class_name = classification_categories[top1_class_id]
773
+ top1_class_score = classifications[0][1]
774
+
775
+ # If we either don't have a confidence threshold, or we've met our
776
+ # confidence threshold
777
+ if (options.classification_confidence_threshold < 0) or \
778
+ (top1_class_score >= options.classification_confidence_threshold):
779
+ image_result.append(['class_{}'.format(top1_class_name),
780
+ rendered_image_html_info])
781
+ else:
782
+ image_result.append(['class_unreliable',
783
+ rendered_image_html_info])
784
+
785
+ # ...if this detection has classification info
786
+
787
+ # ...for each detection
788
+
789
+ image_result[0][1]['max_conf'] = max_conf
790
+
791
+ # ...if we got valid rendering info back from _render_bounding_boxes()
792
+
793
+ return image_result
794
+
795
+ # ...def _render_image_no_gt()
796
+
797
+
798
+ def _render_image_with_gt(file_info,ground_truth_indexed_db,
799
+ detection_categories,classification_categories,options):
800
+ """
801
+ Render an image with ground truth information. See _render_image_no_gt for return
802
+ data format.
803
+ """
804
+
805
+ image_relative_path = file_info[0]
806
+ max_conf = file_info[1]
807
+ detections = file_info[2]
808
+
809
+ # This should already have been normalized to either '/' or '\'
810
+
811
+ image_id = ground_truth_indexed_db.filename_to_id.get(image_relative_path, None)
812
+ if image_id is None:
813
+ print('Warning: couldn''t find ground truth for image {}'.format(image_relative_path))
814
+ return None
815
+
816
+ image = ground_truth_indexed_db.image_id_to_image[image_id]
817
+ annotations = ground_truth_indexed_db.image_id_to_annotations[image_id]
818
+
819
+ ground_truth_boxes = []
820
+ for ann in annotations:
821
+ if 'bbox' in ann:
822
+ ground_truth_box = [x for x in ann['bbox']]
823
+ ground_truth_box.append(ann['category_id'])
824
+ ground_truth_boxes.append(ground_truth_box)
825
+
826
+ gt_status = image['_detection_status']
827
+
828
+ gt_presence = bool(gt_status)
829
+
830
+ gt_classes = CameraTrapJsonUtils.annotations_to_class_names(
831
+ annotations, ground_truth_indexed_db.cat_id_to_name)
832
+ gt_class_summary = ','.join(gt_classes)
833
+
834
+ if gt_status > DetectionStatus.DS_MAX_DEFINITIVE_VALUE:
835
+ print(f'Skipping image {image_id}, does not have a definitive '
836
+ f'ground truth status (status: {gt_status}, classes: {gt_class_summary})')
837
+ return None
838
+
839
+ detected = _has_positive_detection(detections, options, detection_categories)
840
+
841
+ if gt_presence and detected:
842
+ if '_classification_accuracy' not in image.keys():
843
+ res = 'tp'
844
+ elif np.isclose(1, image['_classification_accuracy']):
845
+ res = 'tpc'
846
+ else:
847
+ res = 'tpi'
848
+ elif not gt_presence and detected:
849
+ res = 'fp'
850
+ elif gt_presence and not detected:
851
+ res = 'fn'
852
+ else:
853
+ res = 'tn'
854
+
855
+ display_name = '<b>Result type</b>: {}, <b>Presence</b>: {}, <b>Class</b>: {}, <b>Max conf</b>: {:0.3f}%, <b>Image</b>: {}'.format(
856
+ res.upper(), str(gt_presence), gt_class_summary,
857
+ max_conf * 100, image_relative_path)
858
+
859
+ rendered_image_html_info = _render_bounding_boxes(
860
+ image_base_dir=options.image_base_dir,
861
+ image_relative_path=image_relative_path,
862
+ display_name=display_name,
863
+ detections=detections,
864
+ res=res,
865
+ ground_truth_boxes=ground_truth_boxes,
866
+ detection_categories=detection_categories,
867
+ classification_categories=classification_categories,
868
+ options=options)
869
+
870
+ image_result = None
871
+ if len(rendered_image_html_info) > 0:
872
+ image_result = [[res, rendered_image_html_info]]
873
+ for gt_class in gt_classes:
874
+ image_result.append(['class_{}'.format(gt_class), rendered_image_html_info])
875
+
876
+ return image_result
877
+
878
+ # ...def _render_image_with_gt()
879
+
880
+
881
+ #%% Main function
882
+
883
+ def process_batch_results(options):
884
+
885
+ """
886
+ Given a .json or .csv file containing MD results, do one or more of the following:
887
+
888
+ * Sample detections/non-detections and render to HTML (when ground truth isn't
889
+ available) (this is 99.9% of what this module is for)
890
+ * Evaluate detector precision/recall, optionally rendering results (requires
891
+ ground truth)
892
+ * Sample true/false positives/negatives and render to HTML (requires ground
893
+ truth)
894
+
895
+ Ground truth, if available, must be in COCO Camera Traps format:
896
+
897
+ https://github.com/agentmorris/MegaDetector/blob/main/megadetector/data_management/README.md#coco-camera-traps-format
898
+
899
+ Args:
900
+ options (PostProcessingOptions): everything we need to render a preview/analysis for
901
+ this set of results; see the PostProcessingOptions class for details.
902
+
903
+ Returns:
904
+ PostProcessingResults: information about the results/preview, most importantly the HTML filename
905
+ of the output. See the PostProcessingResults class for details.
906
+ """
907
+ ppresults = PostProcessingResults()
908
+
909
+ ##%% Expand some options for convenience
910
+
911
+ output_dir = options.output_dir
912
+
913
+
914
+ ##%% Prepare output dir
915
+
916
+ os.makedirs(output_dir, exist_ok=True)
917
+
918
+
919
+ ##%% Load ground truth if available
920
+
921
+ ground_truth_indexed_db = None
922
+
923
+ if (options.ground_truth_json_file is not None) and (len(options.ground_truth_json_file) > 0):
924
+ assert (options.confidence_threshold is None) or (isinstance(options.confidence_threshold,float)), \
925
+ 'Variable confidence thresholds are not supported when supplying ground truth'
926
+
927
+ if (options.ground_truth_json_file is not None) and (len(options.ground_truth_json_file) > 0):
928
+
929
+ if options.separate_detections_by_category:
930
+ print("Warning: I don't know how to separate categories yet when doing " + \
931
+ "a P/R analysis, disabling category separation")
932
+ options.separate_detections_by_category = False
933
+
934
+ ground_truth_indexed_db = IndexedJsonDb(
935
+ options.ground_truth_json_file, b_normalize_paths=True,
936
+ filename_replacements=options.ground_truth_filename_replacements)
937
+
938
+ # Mark images in the ground truth as positive or negative
939
+ n_negative, n_positive, n_unknown, n_ambiguous = _mark_detection_status(
940
+ ground_truth_indexed_db, negative_classes=options.negative_classes,
941
+ unknown_classes=options.unlabeled_classes)
942
+ print(f'Finished loading and indexing ground truth: {n_negative} '
943
+ f'negative, {n_positive} positive, {n_unknown} unknown, '
944
+ f'{n_ambiguous} ambiguous')
945
+
946
+
947
+ ##%% Load detection (and possibly classification) results
948
+
949
+ # If the caller hasn't supplied results, load them
950
+ if options.api_detection_results is None:
951
+ detections_df, other_fields = load_api_results(
952
+ options.md_results_file, force_forward_slashes=True,
953
+ filename_replacements=options.api_output_filename_replacements)
954
+ ppresults.api_detection_results = detections_df
955
+ ppresults.api_other_fields = other_fields
956
+
957
+ else:
958
+ print('Bypassing detection results loading...')
959
+ assert options.api_other_fields is not None
960
+ detections_df = options.api_detection_results
961
+ other_fields = options.api_other_fields
962
+
963
+ # Determine confidence thresholds if necessary
964
+
965
+ if options.confidence_threshold is None:
966
+ options.confidence_threshold = \
967
+ get_typical_confidence_threshold_from_results(other_fields)
968
+ print('Choosing default confidence threshold of {} based on MD version'.format(
969
+ options.confidence_threshold))
970
+
971
+ if options.almost_detection_confidence_threshold is None and options.include_almost_detections:
972
+ assert isinstance(options.confidence_threshold,float), \
973
+ 'If you are using a dictionary of confidence thresholds and almost-detections are enabled, ' + \
974
+ 'you need to supply a threshold for almost detections.'
975
+ options.almost_detection_confidence_threshold = options.confidence_threshold - 0.05
976
+ if options.almost_detection_confidence_threshold < 0:
977
+ options.almost_detection_confidence_threshold = 0
978
+
979
+ # Remove rows with inference failures (typically due to corrupt images)
980
+ n_failures = 0
981
+ if 'failure' in detections_df.columns:
982
+ n_failures = detections_df['failure'].count()
983
+ print('Ignoring {} failed images'.format(n_failures))
984
+ # Explicitly forcing a copy() operation here to suppress "trying to be set
985
+ # on a copy" warnings (and associated risks) below.
986
+ detections_df = detections_df[detections_df['failure'].isna()].copy()
987
+
988
+ assert other_fields is not None
989
+
990
+ detection_categories = other_fields['detection_categories']
991
+
992
+ # Convert keys and values to lowercase
993
+ classification_categories = other_fields.get('classification_categories', {})
994
+ if classification_categories is not None:
995
+ classification_categories = {
996
+ k.lower(): v.lower()
997
+ for k, v in classification_categories.items()
998
+ }
999
+
1000
+ # Count detections and almost-detections for reporting purposes
1001
+ n_positives = 0
1002
+ n_almosts = 0
1003
+
1004
+ for i_row,row in tqdm(detections_df.iterrows(),total=len(detections_df)):
1005
+
1006
+ detections = row['detections']
1007
+ max_conf = row['max_detection_conf']
1008
+ if _has_positive_detection(detections, options, detection_categories):
1009
+ n_positives += 1
1010
+ elif (options.almost_detection_confidence_threshold is not None) and \
1011
+ (max_conf >= options.almost_detection_confidence_threshold):
1012
+ n_almosts += 1
1013
+
1014
+ print(f'Finished loading and preprocessing {len(detections_df)} rows '
1015
+ f'from detector output, predicted {n_positives} positives.')
1016
+
1017
+ if options.include_almost_detections:
1018
+ print('...and {} almost-positives'.format(n_almosts))
1019
+
1020
+
1021
+ ##%% Find descriptive metadata to include at the top of the page
1022
+
1023
+ if options.job_name_string is not None:
1024
+ job_name_string = options.job_name_string
1025
+ else:
1026
+ # This is rare; it only happens during debugging when the caller
1027
+ # is supplying already-loaded MD results.
1028
+ if options.md_results_file is None:
1029
+ job_name_string = 'unknown'
1030
+ else:
1031
+ job_name_string = os.path.basename(options.md_results_file)
1032
+
1033
+ if options.model_version_string is not None:
1034
+ model_version_string = options.model_version_string
1035
+ else:
1036
+
1037
+ if 'info' not in other_fields or 'detector' not in other_fields['info']:
1038
+ print('No model metadata supplied, assuming MDv4')
1039
+ model_version_string = 'MDv4 (assumed)'
1040
+ else:
1041
+ model_version_string = other_fields['info']['detector']
1042
+
1043
+
1044
+ ##%% If we have ground truth, remove images we can't match to ground truth
1045
+
1046
+ if ground_truth_indexed_db is not None:
1047
+
1048
+ b_match = detections_df['file'].isin(
1049
+ ground_truth_indexed_db.filename_to_id)
1050
+ print(f'Confirmed filename matches to ground truth for {sum(b_match)} '
1051
+ f'of {len(detections_df)} files')
1052
+
1053
+ detections_df = detections_df[b_match]
1054
+ detector_files = detections_df['file'].tolist()
1055
+
1056
+ assert len(detector_files) > 0, (
1057
+ 'No detection files available, possible path issue?')
1058
+
1059
+ print('Trimmed detection results to {} files'.format(len(detector_files)))
1060
+
1061
+
1062
+ ##%% (Optionally) sample from the full set of images
1063
+
1064
+ images_to_visualize = detections_df
1065
+
1066
+ if options.num_images_to_sample is not None and options.num_images_to_sample > 0:
1067
+ images_to_visualize = images_to_visualize.sample(
1068
+ n=min(options.num_images_to_sample, len(images_to_visualize)),
1069
+ random_state=options.sample_seed)
1070
+
1071
+ output_html_file = ''
1072
+
1073
+ style_header = """<head>
1074
+ <style type="text/css">
1075
+ a { text-decoration: none; }
1076
+ body { font-family: segoe ui, calibri, "trebuchet ms", verdana, arial, sans-serif; }
1077
+ div.contentdiv { margin-left: 20px; }
1078
+ </style>
1079
+ </head>"""
1080
+
1081
+
1082
+ ##%% Fork here depending on whether or not ground truth is available
1083
+
1084
+ # If we have ground truth, we'll compute precision/recall and sample tp/fp/tn/fn.
1085
+ #
1086
+ # Otherwise we'll just visualize detections/non-detections.
1087
+
1088
+ if ground_truth_indexed_db is not None:
1089
+
1090
+ ##%% Detection evaluation: compute precision/recall
1091
+
1092
+ # numpy array of detection probabilities
1093
+ p_detection = detections_df['max_detection_conf'].values
1094
+ n_detections = len(p_detection)
1095
+
1096
+ # numpy array of bools (0.0/1.0), and -1 as null value
1097
+ gt_detections = np.zeros(n_detections, dtype=float)
1098
+
1099
+ for i_detection, fn in enumerate(detector_files):
1100
+ image_id = ground_truth_indexed_db.filename_to_id[fn]
1101
+ image = ground_truth_indexed_db.image_id_to_image[image_id]
1102
+ detection_status = image['_detection_status']
1103
+
1104
+ if detection_status == DetectionStatus.DS_NEGATIVE:
1105
+ gt_detections[i_detection] = 0.0
1106
+ elif detection_status == DetectionStatus.DS_POSITIVE:
1107
+ gt_detections[i_detection] = 1.0
1108
+ else:
1109
+ gt_detections[i_detection] = -1.0
1110
+
1111
+ # Don't include ambiguous/unknown ground truth in precision/recall analysis
1112
+ b_valid_ground_truth = gt_detections >= 0.0
1113
+
1114
+ p_detection_pr = p_detection[b_valid_ground_truth]
1115
+ gt_detections_pr = (gt_detections[b_valid_ground_truth] == 1.)
1116
+
1117
+ print('Including {} of {} values in p/r analysis'.format(np.sum(b_valid_ground_truth),
1118
+ len(b_valid_ground_truth)))
1119
+
1120
+ precisions, recalls, thresholds = precision_recall_curve(gt_detections_pr, p_detection_pr)
1121
+
1122
+ # For completeness, include the result at a confidence threshold of 1.0
1123
+ thresholds = np.append(thresholds, [1.0])
1124
+
1125
+ precisions_recalls = pd.DataFrame(data={
1126
+ 'confidence_threshold': thresholds,
1127
+ 'precision': precisions,
1128
+ 'recall': recalls
1129
+ })
1130
+
1131
+ # Compute and print summary statistics
1132
+ average_precision = average_precision_score(gt_detections_pr, p_detection_pr)
1133
+ print('Average precision: {:.1%}'.format(average_precision))
1134
+
1135
+ # Thresholds go up throughout precisions/recalls/thresholds; find the last
1136
+ # value where recall is at or above target. That's our precision @ target recall.
1137
+
1138
+ i_above_target_recall = (np.where(recalls >= options.target_recall))
1139
+
1140
+ # np.where returns a tuple of arrays, but in this syntax where we're
1141
+ # comparing an array with a scalar, there will only be one element.
1142
+ assert len (i_above_target_recall) == 1
1143
+
1144
+ # Convert back to a list
1145
+ i_above_target_recall = i_above_target_recall[0].tolist()
1146
+
1147
+ if len(i_above_target_recall) == 0:
1148
+ precision_at_target_recall = 0.0
1149
+ else:
1150
+ precision_at_target_recall = precisions[i_above_target_recall[-1]]
1151
+ print('Precision at {:.1%} recall: {:.1%}'.format(options.target_recall,
1152
+ precision_at_target_recall))
1153
+
1154
+ cm_predictions = np.array(p_detection_pr) > options.confidence_threshold
1155
+ cm = confusion_matrix(gt_detections_pr, cm_predictions, labels=[False,True])
1156
+
1157
+ # Flatten the confusion matrix
1158
+ tn, fp, fn, tp = cm.ravel()
1159
+
1160
+ precision_at_confidence_threshold = tp / (tp + fp)
1161
+ recall_at_confidence_threshold = tp / (tp + fn)
1162
+ f1 = 2.0 * (precision_at_confidence_threshold * recall_at_confidence_threshold) / \
1163
+ (precision_at_confidence_threshold + recall_at_confidence_threshold)
1164
+
1165
+ print('At a confidence threshold of {:.1%}, precision={:.1%}, recall={:.1%}, f1={:.1%}'.format(
1166
+ options.confidence_threshold, precision_at_confidence_threshold,
1167
+ recall_at_confidence_threshold, f1))
1168
+
1169
+ ##%% Collect classification results, if they exist
1170
+
1171
+ classifier_accuracies = []
1172
+
1173
+ # Mapping of classnames to idx for the confusion matrix.
1174
+ #
1175
+ # The lambda is actually kind of a hack, because we use assume that
1176
+ # the following code does not reassign classname_to_idx
1177
+ classname_to_idx = collections.defaultdict(lambda: len(classname_to_idx))
1178
+
1179
+ # Confusion matrix as defaultdict of defaultdict
1180
+ #
1181
+ # Rows / first index is ground truth, columns / second index is predicted category
1182
+ classifier_cm = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))
1183
+
1184
+ # iDetection = 0; fn = detector_files[iDetection]; print(fn)
1185
+ assert len(detector_files) == len(detections_df)
1186
+ for iDetection, fn in enumerate(detector_files):
1187
+
1188
+ image_id = ground_truth_indexed_db.filename_to_id[fn]
1189
+ image = ground_truth_indexed_db.image_id_to_image[image_id]
1190
+ detections = detections_df['detections'].iloc[iDetection]
1191
+ pred_class_ids = [det['classifications'][0][0] \
1192
+ for det in detections if 'classifications' in det.keys()]
1193
+ pred_classnames = [classification_categories[pd] for pd in pred_class_ids]
1194
+
1195
+ # If this image has classification predictions, and an unambiguous class
1196
+ # annotated, and is a positive image...
1197
+ if len(pred_classnames) > 0 \
1198
+ and '_unambiguous_category' in image.keys() \
1199
+ and image['_detection_status'] == DetectionStatus.DS_POSITIVE:
1200
+
1201
+ # The unambiguous category, we make this a set for easier handling afterward
1202
+ gt_categories = set([image['_unambiguous_category']])
1203
+ pred_categories = set(pred_classnames)
1204
+
1205
+ # Compute the accuracy as intersection of union,
1206
+ # i.e. (# of categories in both prediction and GT)
1207
+ # divided by (# of categories in either prediction or GT
1208
+ #
1209
+ # In case of only one GT category, the result will be 1.0, if
1210
+ # prediction is one category and this category matches GT
1211
+ #
1212
+ # It is 1.0/(# of predicted top-1 categories), if the GT is
1213
+ # one of the predicted top-1 categories.
1214
+ #
1215
+ # It is 0.0, if none of the predicted categories is correct
1216
+
1217
+ classifier_accuracies.append(
1218
+ len(gt_categories & pred_categories)
1219
+ / len(gt_categories | pred_categories)
1220
+ )
1221
+ image['_classification_accuracy'] = classifier_accuracies[-1]
1222
+
1223
+ # Distribute this accuracy across all predicted categories in the
1224
+ # confusion matrix
1225
+ assert len(gt_categories) == 1
1226
+ gt_class_idx = classname_to_idx[list(gt_categories)[0]]
1227
+ for pred_category in pred_categories:
1228
+ pred_class_idx = classname_to_idx[pred_category]
1229
+ classifier_cm[gt_class_idx][pred_class_idx] += 1
1230
+
1231
+ # ...for each file in the detection results
1232
+
1233
+ # If we have classification results
1234
+ if len(classifier_accuracies) > 0:
1235
+
1236
+ # Build confusion matrix as array from classifier_cm
1237
+ all_class_ids = sorted(classname_to_idx.values())
1238
+ classifier_cm_array = np.array(
1239
+ [[classifier_cm[r_idx][c_idx] for c_idx in all_class_ids] for \
1240
+ r_idx in all_class_ids], dtype=float)
1241
+ classifier_cm_array /= (classifier_cm_array.sum(axis=1, keepdims=True) + 1e-7)
1242
+
1243
+ # Print some statistics
1244
+ print('Finished computation of {} classification results'.format(
1245
+ len(classifier_accuracies)))
1246
+ print('Mean accuracy: {}'.format(np.mean(classifier_accuracies)))
1247
+
1248
+ # Prepare confusion matrix output
1249
+
1250
+ # Get confusion matrix as string
1251
+ sio = io.StringIO()
1252
+ np.savetxt(sio, classifier_cm_array * 100, fmt='%5.1f')
1253
+ cm_str = sio.getvalue()
1254
+ # Get fixed-size classname for each idx
1255
+ idx_to_classname = {v:k for k,v in classname_to_idx.items()}
1256
+ classname_list = [idx_to_classname[idx] for idx in sorted(classname_to_idx.values())]
1257
+ classname_headers = ['{:<5}'.format(cname[:5]) for cname in classname_list]
1258
+
1259
+ # Prepend class name on each line and add to the top
1260
+ cm_str_lines = [' ' * 16 + ' '.join(classname_headers)]
1261
+ cm_str_lines += ['{:>15}'.format(cn[:15]) + ' ' + cm_line for cn, cm_line in \
1262
+ zip(classname_list, cm_str.splitlines())]
1263
+
1264
+ # Print formatted confusion matrix
1265
+ if False:
1266
+ # Actually don't, this gets really messy in all but the widest consoles
1267
+ print('Confusion matrix: ')
1268
+ print(*cm_str_lines, sep='\n')
1269
+
1270
+ # Plot confusion matrix
1271
+
1272
+ # To manually add more space at bottom: plt.rcParams['figure.subplot.bottom'] = 0.1
1273
+ #
1274
+ # Add 0.5 to figsize for every class. For two classes, this will result in
1275
+ # fig = plt.figure(figsize=[4,4])
1276
+ fig = plot_utils.plot_confusion_matrix(
1277
+ classifier_cm_array,
1278
+ classname_list,
1279
+ normalize=False,
1280
+ title='Confusion matrix',
1281
+ cmap=plt.cm.Blues,
1282
+ vmax=1.0,
1283
+ use_colorbar=True,
1284
+ y_label=True)
1285
+ cm_figure_relative_filename = 'confusion_matrix.png'
1286
+ cm_figure_filename = os.path.join(output_dir, cm_figure_relative_filename)
1287
+ plt.savefig(cm_figure_filename)
1288
+ plt.close(fig)
1289
+
1290
+ # ...if we have classification results
1291
+
1292
+
1293
+ ##%% Render output
1294
+
1295
+ # Write p/r table to .csv file in output directory
1296
+ pr_table_filename = os.path.join(output_dir, 'prec_recall.csv')
1297
+ precisions_recalls.to_csv(pr_table_filename, index=False)
1298
+
1299
+ # Write precision/recall plot to .png file in output directory
1300
+ t = 'Precision-Recall curve: AP={:0.1%}, P@{:0.1%}={:0.1%}'.format(
1301
+ average_precision, options.target_recall, precision_at_target_recall)
1302
+ fig = plot_utils.plot_precision_recall_curve(precisions, recalls, t)
1303
+
1304
+ pr_figure_relative_filename = 'prec_recall.png'
1305
+ pr_figure_filename = os.path.join(output_dir, pr_figure_relative_filename)
1306
+ fig.savefig(pr_figure_filename)
1307
+ plt.close(fig)
1308
+
1309
+
1310
+ ##%% Sampling
1311
+
1312
+ # Sample true/false positives/negatives with correct/incorrect top-1
1313
+ # classification and render to html
1314
+
1315
+ # Accumulate html image structs (in the format expected by write_html_image_lists)
1316
+ # for each category, e.g. 'tp', 'fp', ..., 'class_bird', ...
1317
+ images_html = collections.defaultdict(list)
1318
+
1319
+ # Add default entries by accessing them for the first time
1320
+ [images_html[res] for res in ['tp', 'tpc', 'tpi', 'fp', 'tn', 'fn']]
1321
+ for res in images_html.keys():
1322
+ os.makedirs(os.path.join(output_dir, res), exist_ok=True)
1323
+
1324
+ image_count = len(images_to_visualize)
1325
+
1326
+ # Each element will be a list of 2-tuples, with elements [collection name,html info struct]
1327
+ rendering_results = []
1328
+
1329
+ # Each element will be a three-tuple with elements file,max_conf,detections
1330
+ files_to_render = []
1331
+
1332
+ # Assemble the information we need for rendering, so we can parallelize without
1333
+ # dealing with Pandas
1334
+ # i_row = 0; row = images_to_visualize.iloc[0]
1335
+ for _, row in images_to_visualize.iterrows():
1336
+
1337
+ # Filenames should already have been normalized to either '/' or '\'
1338
+ files_to_render.append([row['file'], row['max_detection_conf'], row['detections']])
1339
+
1340
+ start_time = time.time()
1341
+ if options.parallelize_rendering:
1342
+ if options.parallelize_rendering_n_cores is None:
1343
+ if options.parallelize_rendering_with_threads:
1344
+ pool = ThreadPool()
1345
+ else:
1346
+ pool = Pool()
1347
+ else:
1348
+ if options.parallelize_rendering_with_threads:
1349
+ pool = ThreadPool(options.parallelize_rendering_n_cores)
1350
+ worker_string = 'threads'
1351
+ else:
1352
+ pool = Pool(options.parallelize_rendering_n_cores)
1353
+ worker_string = 'processes'
1354
+ print('Rendering images with {} {}'.format(options.parallelize_rendering_n_cores,
1355
+ worker_string))
1356
+
1357
+ rendering_results = list(tqdm(pool.imap(
1358
+ partial(_render_image_with_gt,
1359
+ ground_truth_indexed_db=ground_truth_indexed_db,
1360
+ detection_categories=detection_categories,
1361
+ classification_categories=classification_categories,
1362
+ options=options),
1363
+ files_to_render), total=len(files_to_render)))
1364
+ else:
1365
+ for file_info in tqdm(files_to_render):
1366
+ rendering_results.append(_render_image_with_gt(
1367
+ file_info,ground_truth_indexed_db,
1368
+ detection_categories,classification_categories,
1369
+ options=options))
1370
+ elapsed = time.time() - start_time
1371
+
1372
+ # Map all the rendering results in the list rendering_results into the
1373
+ # dictionary images_html, which maps category names to lists of results
1374
+ image_rendered_count = 0
1375
+ for rendering_result in rendering_results:
1376
+ if rendering_result is None:
1377
+ continue
1378
+ image_rendered_count += 1
1379
+ for assignment in rendering_result:
1380
+ images_html[assignment[0]].append(assignment[1])
1381
+
1382
+ # Prepare the individual html image files
1383
+ image_counts = _prepare_html_subpages(images_html, output_dir, options)
1384
+
1385
+ print('{} images rendered (of {})'.format(image_rendered_count,image_count))
1386
+
1387
+ # Write index.html
1388
+ all_tp_count = image_counts['tp'] + image_counts['tpc'] + image_counts['tpi']
1389
+ total_count = all_tp_count + image_counts['tn'] + image_counts['fp'] + image_counts['fn']
1390
+
1391
+ classification_detection_results = """&nbsp;&nbsp;&nbsp;&nbsp;<a href="tpc.html">with all correct top-1 predictions (TPC)</a> ({})<br/>
1392
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="tpi.html">with one or more incorrect top-1 prediction (TPI)</a> ({})<br/>
1393
+ &nbsp;&nbsp;&nbsp;&nbsp;<a href="tp.html">without classification evaluation</a><sup>*</sup> ({})<br/>""".format(
1394
+ image_counts['tpc'],
1395
+ image_counts['tpi'],
1396
+ image_counts['tp']
1397
+ )
1398
+
1399
+ confidence_threshold_string = ''
1400
+ if isinstance(options.confidence_threshold,float):
1401
+ confidence_threshold_string = '{:.2%}'.format(options.confidence_threshold)
1402
+ else:
1403
+ confidence_threshold_string = str(options.confidence_threshold)
1404
+
1405
+ index_page = """<html>
1406
+ {}
1407
+ <body>
1408
+ <h2>Evaluation</h2>
1409
+
1410
+ <h3>Job metadata</h3>
1411
+
1412
+ <div class="contentdiv">
1413
+ <p>Job name: {}<br/>
1414
+ <p>Model version: {}</p>
1415
+ </div>
1416
+
1417
+ <h3>Sample images</h3>
1418
+ <div class="contentdiv">
1419
+ <p>A sample of {} images, annotated with detections above confidence {}.</p>
1420
+ <a href="tp.html">True positives (TP)</a> ({}) ({:0.1%})<br/>
1421
+ CLASSIFICATION_PLACEHOLDER_1
1422
+ <a href="tn.html">True negatives (TN)</a> ({}) ({:0.1%})<br/>
1423
+ <a href="fp.html">False positives (FP)</a> ({}) ({:0.1%})<br/>
1424
+ <a href="fn.html">False negatives (FN)</a> ({}) ({:0.1%})<br/>
1425
+ CLASSIFICATION_PLACEHOLDER_2
1426
+ </div>
1427
+ """.format(
1428
+ style_header,job_name_string,model_version_string,
1429
+ image_count, confidence_threshold_string,
1430
+ all_tp_count, all_tp_count/total_count,
1431
+ image_counts['tn'], image_counts['tn']/total_count,
1432
+ image_counts['fp'], image_counts['fp']/total_count,
1433
+ image_counts['fn'], image_counts['fn']/total_count
1434
+ )
1435
+
1436
+ index_page += """
1437
+ <h3>Detection results</h3>
1438
+ <div class="contentdiv">
1439
+ <p>At a confidence threshold of {}, precision={:0.1%}, recall={:0.1%}</p>
1440
+ <p><strong>Precision/recall summary for all {} images</strong></p><img src="{}"><br/>
1441
+ </div>
1442
+ """.format(
1443
+ confidence_threshold_string, precision_at_confidence_threshold, recall_at_confidence_threshold,
1444
+ len(detections_df), pr_figure_relative_filename
1445
+ )
1446
+
1447
+ if len(classifier_accuracies) > 0:
1448
+ index_page = index_page.replace('CLASSIFICATION_PLACEHOLDER_1',classification_detection_results)
1449
+ index_page = index_page.replace('CLASSIFICATION_PLACEHOLDER_2',"""<p><sup>*</sup>We do not evaluate the classification result of images
1450
+ if the classification information is missing, if the image contains
1451
+ categories like &lsquo;empty&rsquo; or &lsquo;human&rsquo;, or if the image has multiple
1452
+ classification labels.</p>""")
1453
+ else:
1454
+ index_page = index_page.replace('CLASSIFICATION_PLACEHOLDER_1','')
1455
+ index_page = index_page.replace('CLASSIFICATION_PLACEHOLDER_2','')
1456
+
1457
+ if len(classifier_accuracies) > 0:
1458
+ index_page += """
1459
+ <h3>Classification results</h3>
1460
+ <div class="contentdiv">
1461
+ <p>Classification accuracy: {:.2%}<br>
1462
+ The accuracy is computed only for images with exactly one classification label.
1463
+ The accuracy of an image is computed as 1/(number of unique detected top-1 classes),
1464
+ i.e. if the model detects multiple boxes with different top-1 classes, then the accuracy
1465
+ decreases and the image is put into 'TPI'.</p>
1466
+ <p>Confusion matrix:</p>
1467
+ <p><img src="{}"></p>
1468
+ <div style='font-family:monospace;display:block;'>{}</div>
1469
+ </div>
1470
+ """.format(
1471
+ np.mean(classifier_accuracies),
1472
+ cm_figure_relative_filename,
1473
+ "<br>".join(cm_str_lines).replace(' ', '&nbsp;')
1474
+ )
1475
+
1476
+ # Show links to each GT class
1477
+ #
1478
+ # We could do this without classification results; currently we don't.
1479
+ if len(classname_to_idx) > 0:
1480
+
1481
+ index_page += '<h3>Images of specific classes</h3><br/><div class="contentdiv">'
1482
+ # Add links to all available classes
1483
+ for cname in sorted(classname_to_idx.keys()):
1484
+ index_page += '<a href="class_{0}.html">{0}</a> ({1})<br>'.format(
1485
+ cname,
1486
+ len(images_html['class_{}'.format(cname)]))
1487
+ index_page += '</div>'
1488
+
1489
+ # Close body and html tags
1490
+ index_page += '</body></html>'
1491
+ output_html_file = os.path.join(output_dir, 'index.html')
1492
+ with open(output_html_file, 'w') as f:
1493
+ f.write(index_page)
1494
+
1495
+ print('Finished writing html to {}'.format(output_html_file))
1496
+
1497
+ # ...for each image
1498
+
1499
+
1500
+ ##%% Otherwise, if we don't have ground truth...
1501
+
1502
+ else:
1503
+
1504
+ ##%% Sample detections/non-detections
1505
+
1506
+ # Accumulate html image structs (in the format expected by write_html_image_list)
1507
+ # for each category
1508
+ images_html = collections.defaultdict(list)
1509
+
1510
+
1511
+ # Add default entries by accessing them for the first time
1512
+
1513
+ # Maps sorted tuples of detection category IDs (string ints) - e.g. ("1"), ("1", "4", "7") - to
1514
+ # result set names, e.g. "detections_human", "detections_cat_truck".
1515
+ detection_categories_to_results_name = {}
1516
+
1517
+ # Keep track of which categories are single-class (e.g. "animal") and which are
1518
+ # combinations (e.g. "animal_vehicle")
1519
+ detection_categories_to_category_count = {}
1520
+
1521
+ # For the creation of a "non-detections" category
1522
+ images_html['non_detections']
1523
+ detection_categories_to_category_count['non_detections'] = 0
1524
+
1525
+
1526
+ if not options.separate_detections_by_category:
1527
+ # For the creation of a "detections" category
1528
+ images_html['detections']
1529
+ detection_categories_to_category_count['detections'] = 0
1530
+ else:
1531
+ # Add a set of results for each category and combination of categories, e.g.
1532
+ # "detections_animal_vehicle". When we're using this script for non-MegaDetector
1533
+ # results, this can generate lots of categories, e.g. detections_bear_bird_cat_dog_pig.
1534
+ # We'll keep that huge set of combinations in this map, but we'll only write
1535
+ # out links for the ones that are non-empty.
1536
+ used_combinations = set()
1537
+
1538
+ # row = images_to_visualize.iloc[0]
1539
+ for i_row, row in images_to_visualize.iterrows():
1540
+ detections_this_row = row['detections']
1541
+ above_threshold_category_ids_this_row = set()
1542
+ for detection in detections_this_row:
1543
+ threshold = _get_threshold_for_category_id(detection['category'], options, detection_categories)
1544
+ if detection['conf'] >= threshold:
1545
+ above_threshold_category_ids_this_row.add(detection['category'])
1546
+ if len(above_threshold_category_ids_this_row) == 0:
1547
+ continue
1548
+ sorted_categories_this_row = tuple(sorted(above_threshold_category_ids_this_row))
1549
+ used_combinations.add(sorted_categories_this_row)
1550
+
1551
+ for sorted_subset in used_combinations:
1552
+ assert len(sorted_subset) > 0
1553
+ results_name = 'detections'
1554
+ for category_id in sorted_subset:
1555
+ results_name = results_name + '_' + detection_categories[category_id]
1556
+ images_html[results_name]
1557
+ detection_categories_to_results_name[sorted_subset] = results_name
1558
+ detection_categories_to_category_count[results_name] = len(sorted_subset)
1559
+
1560
+ if options.include_almost_detections:
1561
+ images_html['almost_detections']
1562
+ detection_categories_to_category_count['almost_detections'] = 0
1563
+
1564
+ # Create output directories
1565
+ for res in images_html.keys():
1566
+ os.makedirs(os.path.join(output_dir, res), exist_ok=True)
1567
+
1568
+ image_count = len(images_to_visualize)
1569
+
1570
+ # Each element will be a list of 2-tuples, with elements [collection name,html info struct]
1571
+ rendering_results = []
1572
+
1573
+ # list of 3-tuples with elements (file, max_conf, detections)
1574
+ files_to_render = []
1575
+
1576
+ # Assemble the information we need for rendering, so we can parallelize without
1577
+ # dealing with Pandas
1578
+ # i_row = 0; row = images_to_visualize.iloc[0]
1579
+ for _, row in images_to_visualize.iterrows():
1580
+
1581
+ assert isinstance(row['detections'],list)
1582
+
1583
+ # Filenames should already have been normalized to either '/' or '\'
1584
+ files_to_render.append([row['file'],
1585
+ row['max_detection_conf'],
1586
+ row['detections']])
1587
+
1588
+ start_time = time.time()
1589
+ if options.parallelize_rendering:
1590
+
1591
+ if options.parallelize_rendering_n_cores is None:
1592
+ if options.parallelize_rendering_with_threads:
1593
+ pool = ThreadPool()
1594
+ else:
1595
+ pool = Pool()
1596
+ else:
1597
+ if options.parallelize_rendering_with_threads:
1598
+ pool = ThreadPool(options.parallelize_rendering_n_cores)
1599
+ worker_string = 'threads'
1600
+ else:
1601
+ pool = Pool(options.parallelize_rendering_n_cores)
1602
+ worker_string = 'processes'
1603
+ print('Rendering images with {} {}'.format(options.parallelize_rendering_n_cores,
1604
+ worker_string))
1605
+
1606
+ # _render_image_no_gt(file_info,detection_categories_to_results_name,
1607
+ # detection_categories,classification_categories)
1608
+
1609
+ rendering_results = list(tqdm(pool.imap(
1610
+ partial(_render_image_no_gt,
1611
+ detection_categories_to_results_name=detection_categories_to_results_name,
1612
+ detection_categories=detection_categories,
1613
+ classification_categories=classification_categories,
1614
+ options=options),
1615
+ files_to_render), total=len(files_to_render)))
1616
+ else:
1617
+ for file_info in tqdm(files_to_render):
1618
+ rendering_results.append(_render_image_no_gt(file_info,
1619
+ detection_categories_to_results_name,
1620
+ detection_categories,
1621
+ classification_categories,
1622
+ options=options))
1623
+
1624
+ elapsed = time.time() - start_time
1625
+
1626
+ # Do we have classification results in addition to detection results?
1627
+ has_classification_info = False
1628
+
1629
+ # Map all the rendering results in the list rendering_results into the
1630
+ # dictionary images_html
1631
+ image_rendered_count = 0
1632
+ for rendering_result in rendering_results:
1633
+ if rendering_result is None:
1634
+ continue
1635
+ image_rendered_count += 1
1636
+ for assignment in rendering_result:
1637
+ if 'class' in assignment[0]:
1638
+ has_classification_info = True
1639
+ images_html[assignment[0]].append(assignment[1])
1640
+
1641
+ # Prepare the individual html image files
1642
+ image_counts = _prepare_html_subpages(images_html, output_dir, options)
1643
+
1644
+ if image_rendered_count == 0:
1645
+ seconds_per_image = 0.0
1646
+ else:
1647
+ seconds_per_image = elapsed/image_rendered_count
1648
+
1649
+ print('Rendered {} images (of {}) in {} ({} per image)'.format(image_rendered_count,
1650
+ image_count,humanfriendly.format_timespan(elapsed),
1651
+ humanfriendly.format_timespan(seconds_per_image)))
1652
+
1653
+ # Write index.html
1654
+
1655
+ # We can't just sum these, because image_counts includes images in both their
1656
+ # detection and classification classes
1657
+ # total_images = sum(image_counts.values())
1658
+ total_images = 0
1659
+ for k in image_counts.keys():
1660
+ v = image_counts[k]
1661
+ if has_classification_info and k.startswith('class_'):
1662
+ continue
1663
+ total_images += v
1664
+
1665
+ if total_images != image_count:
1666
+ print('Warning, missing images: image_count is {}, total_images is {}'.format(total_images,image_count))
1667
+
1668
+ almost_detection_string = ''
1669
+ if options.include_almost_detections:
1670
+ almost_detection_string = ' (&ldquo;almost detection&rdquo; threshold at {:.1%})'.format(
1671
+ options.almost_detection_confidence_threshold)
1672
+
1673
+ confidence_threshold_string = ''
1674
+ if isinstance(options.confidence_threshold,float):
1675
+ confidence_threshold_string = '{:.2%}'.format(options.confidence_threshold)
1676
+ else:
1677
+ confidence_threshold_string = str(options.confidence_threshold)
1678
+
1679
+ index_page = """<html>\n{}\n<body>\n
1680
+ <h2>Visualization of results for {}</h2>\n
1681
+ <p>A sample of {} images (of {} total)FAILURE_PLACEHOLDER, annotated with detections above confidence {}{}.</p>\n
1682
+
1683
+ <div class="contentdiv">
1684
+ <p>Model version: {}</p>
1685
+ </div>
1686
+
1687
+ <h3>Sample images</h3>\n
1688
+ <div class="contentdiv">\n""".format(
1689
+ style_header, job_name_string, image_count, len(detections_df), confidence_threshold_string,
1690
+ almost_detection_string, model_version_string)
1691
+
1692
+ failure_string = ''
1693
+ if n_failures is not None:
1694
+ failure_string = ' ({} failures)'.format(n_failures)
1695
+ index_page = index_page.replace('FAILURE_PLACEHOLDER',failure_string)
1696
+
1697
+ def result_set_name_to_friendly_name(result_set_name):
1698
+ friendly_name = ''
1699
+ friendly_name = result_set_name.replace('_','-')
1700
+ if friendly_name.startswith('detections-'):
1701
+ friendly_name = friendly_name.replace('detections-', 'detections: ')
1702
+ friendly_name = friendly_name.capitalize()
1703
+ return friendly_name
1704
+
1705
+ sorted_result_set_names = sorted(list(images_html.keys()))
1706
+
1707
+ result_set_name_to_count = {}
1708
+ for result_set_name in sorted_result_set_names:
1709
+ image_count = image_counts[result_set_name]
1710
+ result_set_name_to_count[result_set_name] = image_count
1711
+ sorted_result_set_names = sorted(sorted_result_set_names,
1712
+ key=lambda x: result_set_name_to_count[x],
1713
+ reverse=True)
1714
+
1715
+ for result_set_name in sorted_result_set_names:
1716
+
1717
+ # Don't print classification classes here; we'll do that later with a slightly
1718
+ # different structure
1719
+ if has_classification_info and result_set_name.lower().startswith('class_'):
1720
+ continue
1721
+
1722
+ filename = result_set_name + '.html'
1723
+ label = result_set_name_to_friendly_name(result_set_name)
1724
+ image_count = image_counts[result_set_name]
1725
+
1726
+ # Don't include line items for empty multi-category pages
1727
+ if image_count == 0 and \
1728
+ detection_categories_to_category_count[result_set_name] > 1:
1729
+ continue
1730
+
1731
+ if total_images == 0:
1732
+ image_fraction = -1
1733
+ else:
1734
+ image_fraction = image_count / total_images
1735
+
1736
+ # Write the line item for this category, including a link only if the
1737
+ # category is non-empty
1738
+ if image_count == 0:
1739
+ index_page += '{} ({}, {:.1%})<br/>\n'.format(
1740
+ label,image_count,image_fraction)
1741
+ else:
1742
+ index_page += '<a href="{}">{}</a> ({}, {:.1%})<br/>\n'.format(
1743
+ filename,label,image_count,image_fraction)
1744
+
1745
+ index_page += '</div>\n'
1746
+
1747
+ if has_classification_info:
1748
+ index_page += '<h3>Images of detected classes</h3>'
1749
+ index_page += '<p>The same image might appear under multiple classes ' + \
1750
+ 'if multiple species were detected.</p>\n'
1751
+ index_page += '<p>Classifications with confidence less than {:.1%} confidence are considered "unreliable".</p>\n'.format(
1752
+ options.classification_confidence_threshold)
1753
+ index_page += '<div class="contentdiv">\n'
1754
+
1755
+ # Add links to all available classes
1756
+ class_names = sorted(classification_categories.values())
1757
+ if 'class_unreliable' in images_html.keys():
1758
+ class_names.append('unreliable')
1759
+
1760
+ if options.sort_classification_results_by_count:
1761
+ class_name_to_count = {}
1762
+ for cname in class_names:
1763
+ ccount = len(images_html['class_{}'.format(cname)])
1764
+ class_name_to_count[cname] = ccount
1765
+ class_names = sorted(class_names,key=lambda x: class_name_to_count[x],reverse=True)
1766
+
1767
+ for cname in class_names:
1768
+ ccount = len(images_html['class_{}'.format(cname)])
1769
+ if ccount > 0:
1770
+ index_page += '<a href="class_{}.html">{}</a> ({})<br/>\n'.format(
1771
+ cname, cname.lower(), ccount)
1772
+ index_page += '</div>\n'
1773
+
1774
+ index_page += '</body></html>'
1775
+ output_html_file = os.path.join(output_dir, 'index.html')
1776
+ with open(output_html_file, 'w') as f:
1777
+ f.write(index_page)
1778
+
1779
+ print('Finished writing html to {}'.format(output_html_file))
1780
+
1781
+ # os.startfile(output_html_file)
1782
+
1783
+ # ...if we do/don't have ground truth
1784
+
1785
+ ppresults.output_html_file = output_html_file
1786
+ return ppresults
1787
+
1788
+ # ...process_batch_results
1789
+
1790
+
1791
+ #%% Interactive driver(s)
1792
+
1793
+ if False:
1794
+
1795
+ #%%
1796
+
1797
+ base_dir = r'g:\temp'
1798
+ options = PostProcessingOptions()
1799
+ options.image_base_dir = base_dir
1800
+ options.output_dir = os.path.join(base_dir, 'preview')
1801
+ options.md_results_file = os.path.join(base_dir, 'results.json')
1802
+ options.confidence_threshold = {'person':0.5,'animal':0.5,'vehicle':0.01}
1803
+ options.include_almost_detections = True
1804
+ options.almost_detection_confidence_threshold = 0.001
1805
+
1806
+ ppresults = process_batch_results(options)
1807
+ # from megadetector.utils.path_utils import open_file; open_file(ppresults.output_html_file)
1808
+
1809
+
1810
+ #%% Command-line driver
1811
+
1812
+ def main():
1813
+
1814
+ options = PostProcessingOptions()
1815
+
1816
+ parser = argparse.ArgumentParser()
1817
+ parser.add_argument(
1818
+ 'md_results_file',
1819
+ help='path to .json file containing MegaDetector results')
1820
+ parser.add_argument(
1821
+ 'output_dir',
1822
+ help='base directory for output')
1823
+ parser.add_argument(
1824
+ '--image_base_dir', default=options.image_base_dir,
1825
+ help='base directory for images (optional, can compute statistics '
1826
+ 'without images)')
1827
+ parser.add_argument(
1828
+ '--ground_truth_json_file', default=options.ground_truth_json_file,
1829
+ help='ground truth labels (optional, can render detections without '
1830
+ 'ground truth), in the COCO Camera Traps format')
1831
+ parser.add_argument(
1832
+ '--confidence_threshold', type=float,
1833
+ default=options.confidence_threshold,
1834
+ help='Confidence threshold for statistics and visualization')
1835
+ parser.add_argument(
1836
+ '--almost_detection_confidence_threshold', type=float,
1837
+ default=options.almost_detection_confidence_threshold,
1838
+ help='Almost-detection confidence threshold for statistics and visualization')
1839
+ parser.add_argument(
1840
+ '--target_recall', type=float, default=options.target_recall,
1841
+ help='Target recall (for statistics only)')
1842
+ parser.add_argument(
1843
+ '--num_images_to_sample', type=int,
1844
+ default=options.num_images_to_sample,
1845
+ help='number of images to visualize, -1 for all images (default: 500)')
1846
+ parser.add_argument(
1847
+ '--viz_target_width', type=int, default=options.viz_target_width,
1848
+ help='Output image width')
1849
+ parser.add_argument(
1850
+ '--include_almost_detections', action='store_true',
1851
+ help='Include a separate category for images just above a second confidence threshold')
1852
+ parser.add_argument(
1853
+ '--html_sort_order', type=str, default='filename',
1854
+ help='Sort order for output pages, should be one of [filename,confidence,random] (defaults to filename)')
1855
+ parser.add_argument(
1856
+ '--sort_by_confidence', action='store_true',
1857
+ help='Sort output in decreasing order by confidence (defaults to sorting by filename)')
1858
+ parser.add_argument(
1859
+ '--n_cores', type=int, default=1,
1860
+ help='Number of threads to use for rendering (default: 1)')
1861
+ parser.add_argument(
1862
+ '--parallelize_rendering_with_processes',
1863
+ action='store_true',
1864
+ help='Should we use processes (instead of threads) for parallelization?')
1865
+ parser.add_argument(
1866
+ '--no_separate_detections_by_category',
1867
+ action='store_true',
1868
+ help='Collapse all categories into just "detections" and "non-detections"')
1869
+ parser.add_argument(
1870
+ '--open_output_file',
1871
+ action='store_true',
1872
+ help='Open the HTML output file when finished')
1873
+ parser.add_argument(
1874
+ '--max_figures_per_html_file',
1875
+ type=int, default=None,
1876
+ help='Maximum number of images to put on a single HTML page')
1877
+
1878
+ if len(sys.argv[1:]) == 0:
1879
+ parser.print_help()
1880
+ parser.exit()
1881
+
1882
+ args = parser.parse_args()
1883
+
1884
+ if args.n_cores != 1:
1885
+ assert (args.n_cores > 1), 'Illegal number of cores: {}'.format(args.n_cores)
1886
+ if args.parallelize_rendering_with_processes:
1887
+ args.parallelize_rendering_with_threads = False
1888
+ args.parallelize_rendering = True
1889
+ args.parallelize_rendering_n_cores = args.n_cores
1890
+
1891
+ args_to_object(args, options)
1892
+
1893
+ if args.no_separate_detections_by_category:
1894
+ options.separate_detections_by_category = False
1895
+
1896
+ ppresults = process_batch_results(options)
1897
+
1898
+ if options.open_output_file:
1899
+ path_utils.open_file(ppresults.output_html_file)
1900
+
1901
+ if __name__ == '__main__':
1902
+ main()