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