-
Notifications
You must be signed in to change notification settings - Fork 26
/
postprocess_batch_results.py
1935 lines (1496 loc) · 78 KB
/
postprocess_batch_results.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
postprocess_batch_results.py
Given a .json or .csv file containing MD results, do one or more of the following:
* Sample detections/non-detections and render to HTML (when ground truth isn't
available) (this is 99.9% of what this module is for)
* Evaluate detector precision/recall, optionally rendering results (requires
ground truth)
* Sample true/false positives/negatives and render to HTML (requires ground
truth)
Ground truth, if available, must be in COCO Camera Traps format:
https://github.com/agentmorris/MegaDetector/blob/main/megadetector/data_management/README.md#coco-camera-traps-format
"""
#%% Constants and imports
import argparse
import collections
import copy
import errno
import io
import os
import sys
import time
import uuid
import warnings
import random
from enum import IntEnum
from multiprocessing.pool import ThreadPool
from multiprocessing.pool import Pool
from functools import partial
import matplotlib.pyplot as plt
import numpy as np
import humanfriendly
import pandas as pd
from sklearn.metrics import precision_recall_curve, confusion_matrix, average_precision_score
from tqdm import tqdm
from megadetector.visualization import visualization_utils as vis_utils
from megadetector.visualization import plot_utils
from megadetector.utils.write_html_image_list import write_html_image_list
from megadetector.utils import path_utils
from megadetector.utils.ct_utils import args_to_object, sets_overlap
from megadetector.data_management.cct_json_utils import (CameraTrapJsonUtils, IndexedJsonDb)
from megadetector.postprocessing.load_api_results import load_api_results
from megadetector.detection.run_detector import get_typical_confidence_threshold_from_results
warnings.filterwarnings('ignore', '(Possibly )?corrupt EXIF data', UserWarning)
#%% Options
DEFAULT_NEGATIVE_CLASSES = ['empty']
DEFAULT_UNKNOWN_CLASSES = ['unknown', 'unlabeled', 'ambiguous']
# Make sure there is no overlap between the two sets, because this will cause
# issues in the code
assert not sets_overlap(DEFAULT_NEGATIVE_CLASSES, DEFAULT_UNKNOWN_CLASSES), (
'Default negative and unknown classes cannot overlap.')
class PostProcessingOptions:
"""
Options used to parameterize process_batch_results().
"""
def __init__(self):
### Required inputs
#: MD results .json file to process
self.md_results_file = ''
#: Folder to which we should write HTML output
self.output_dir = ''
### Options
#: Folder where images live (filenames in [md_results_file] should be relative to this folder)
self.image_base_dir = '.'
## These apply only when we're doing ground-truth comparisons
#: Optional .json file containing ground truth information
self.ground_truth_json_file = ''
#: List of classes we'll treat as negative (defaults to "empty", typically includes
#: classes like "blank", "misfire", etc.).
#:
#: Include the token "#NO_LABELS#" to indicate that an image with no annotations
#: should be considered empty.
self.negative_classes = DEFAULT_NEGATIVE_CLASSES
#: List of classes we'll treat as neither positive nor negative (defaults to
#: "unknown", typically includes classes like "unidentifiable").
self.unlabeled_classes = DEFAULT_UNKNOWN_CLASSES
#: List of output sets that we should count, but not render images for.
#:
#: Typically used to preview sets with lots of empties, where you don't want to
#: subset but also don't want to render 100,000 empty images.
#:
#: detections, non_detections
#: detections_animal, detections_person, detections_vehicle
self.rendering_bypass_sets = []
#: If this is None, choose a confidence threshold based on the detector version.
#:
#: This can either be a float or a dictionary mapping category names (not IDs) to
#: thresholds. The category "default" can be used to specify thresholds for
#: other categories. Currently the use of a dict here is not supported when
#: ground truth is supplied.
self.confidence_threshold = None
#: Confidence threshold to apply to classification (not detection) results
#:
#: Only a float is supported here (unlike the "confidence_threshold" parameter, which
#: can be a dict).
self.classification_confidence_threshold = 0.5
#: Used for summary statistics only
self.target_recall = 0.9
#: Number of images to sample, -1 for "all images"
self.num_images_to_sample = 500
#: Random seed for sampling, or None
self.sample_seed = 0 # None
#: Image width for images in the HTML output
self.viz_target_width = 800
#: Line width (in pixels) for rendering detections
self.line_thickness = 4
#: Box expansion (in pixels) for rendering detections
self.box_expansion = 0
#: Job name to include in big letters in the output HTML
self.job_name_string = None
#: Model version string to include in the output HTML
self.model_version_string = None
#: Sort order for the output, should be one of "filename", "confidence", or "random"
self.html_sort_order = 'filename'
#: If True, images in the output HTML will be links back to the original images
self.link_images_to_originals = True
#: Optionally separate detections into categories (animal/vehicle/human)
#:
#: Currently only supported when ground truth is unavailable
self.separate_detections_by_category = True
#: Optionally replace one or more strings in filenames with other strings;
#: useful for taking a set of results generated for one folder structure
#: and applying them to a slightly different folder structure.
self.api_output_filename_replacements = {}
#: Optionally replace one or more strings in filenames with other strings;
#: useful for taking a set of results generated for one folder structure
#: and applying them to a slightly different folder structure.
self.ground_truth_filename_replacements = {}
#: Allow bypassing API output loading when operating on previously-loaded
#: results. If present, this is a Pandas DataFrame. Almost never useful.
self.api_detection_results = None
#: Allow bypassing API output loading when operating on previously-loaded
#: results. If present, this is a str --> obj dict. Almost never useful.
self.api_other_fields = None
#: Should we also split out a separate report about the detections that were
#: just below our main confidence threshold?
#:
#: Currently only supported when ground truth is unavailable.
self.include_almost_detections = False
#: Only a float is supported here (unlike the "confidence_threshold" parameter, which
#: can be a dict).
self.almost_detection_confidence_threshold = None
#: Enable/disable rendering parallelization
self.parallelize_rendering = False
#: Number of threads/processes to use for rendering parallelization
self.parallelize_rendering_n_cores = 25
#: Whether to use threads (True) or processes (False) for rendering parallelization
self.parallelize_rendering_with_threads = True
#: When classification results are present, should be sort alphabetically by class name (False)
#: or in descending order by frequency (True)?
self.sort_classification_results_by_count = False
#: Should we split individual pages up into smaller pages if there are more than
#: N images?
self.max_figures_per_html_file = None
#: Footer text for the index page
# self.footer_text = '<br/><p style="font-size:80%;">Preview page created with the <a href="{}">MegaDetector Python package</a>.</p>'.\
# format('https://megadetector.readthedocs.io')
self.footer_text = ''
# ...__init__()
# ...PostProcessingOptions
class PostProcessingResults:
"""
Return format from process_batch_results
"""
def __init__(self):
#: HTML file to which preview information was written
self.output_html_file = ''
#: Pandas Dataframe containing detection results
self.api_detection_results = None
#: str --> obj dictionary containing other information loaded from the results file
self.api_other_fields = None
##%% Helper classes and functions
class DetectionStatus(IntEnum):
"""
Flags used to mark images as positive or negative for P/R analysis
(according to ground truth and/or detector output)
:meta private:
"""
DS_NEGATIVE = 0
DS_POSITIVE = 1
# Anything greater than this isn't clearly positive or negative
DS_MAX_DEFINITIVE_VALUE = DS_POSITIVE
# image has annotations suggesting both negative and positive
DS_AMBIGUOUS = 2
# image is not annotated or is annotated with 'unknown', 'unlabeled', ETC.
DS_UNKNOWN = 3
# image has not yet been assigned a state
DS_UNASSIGNED = 4
# In some analyses, we add an additional class that lets us look at
# detections just below our main confidence threshold
DS_ALMOST = 5
def _mark_detection_status(indexed_db,
negative_classes=DEFAULT_NEGATIVE_CLASSES,
unknown_classes=DEFAULT_UNKNOWN_CLASSES):
"""
For each image in indexed_db.db['images'], add a '_detection_status' field
to indicate whether to treat this image as positive, negative, ambiguous,
or unknown.
Makes modifications in-place.
returns (n_negative, n_positive, n_unknown, n_ambiguous)
"""
negative_classes = set(negative_classes)
unknown_classes = set(unknown_classes)
# count the # of images with each type of DetectionStatus
n_unknown = 0
n_ambiguous = 0
n_positive = 0
n_negative = 0
print('Preparing ground-truth annotations')
for im in tqdm(indexed_db.db['images']):
image_id = im['id']
annotations = indexed_db.image_id_to_annotations[image_id]
categories = [ann['category_id'] for ann in annotations]
category_names = set(indexed_db.cat_id_to_name[cat] for cat in categories)
# Check whether this image has:
# - unknown / unassigned-type labels
# - negative-type labels
# - positive labels (i.e., labels that are neither unknown nor negative)
has_unknown_labels = sets_overlap(category_names, unknown_classes)
has_negative_labels = sets_overlap(category_names, negative_classes)
has_positive_labels = 0 < len(category_names - (unknown_classes | negative_classes))
# assert has_unknown_labels is False, '{} has unknown labels'.format(annotations)
# If there are no image annotations...
if len(categories) == 0:
if '#NO_LABELS#' in negative_classes:
n_negative += 1
im['_detection_status'] = DetectionStatus.DS_NEGATIVE
else:
n_unknown += 1
im['_detection_status'] = DetectionStatus.DS_UNKNOWN
# n_negative += 1
# im['_detection_status'] = DetectionStatus.DS_NEGATIVE
# If the image has more than one type of labels, it's ambiguous
# note: bools are automatically converted to 0/1, so we can sum
elif (has_unknown_labels + has_negative_labels + has_positive_labels) > 1:
n_ambiguous += 1
im['_detection_status'] = DetectionStatus.DS_AMBIGUOUS
# After the check above, we can be sure it's only one of positive,
# negative, or unknown.
#
# Important: do not merge the following 'unknown' branch with the first
# 'unknown' branch above, where we tested 'if len(categories) == 0'
#
# If the image has only unknown labels
elif has_unknown_labels:
n_unknown += 1
im['_detection_status'] = DetectionStatus.DS_UNKNOWN
# If the image has only negative labels
elif has_negative_labels:
n_negative += 1
im['_detection_status'] = DetectionStatus.DS_NEGATIVE
# If the images has only positive labels
elif has_positive_labels:
n_positive += 1
im['_detection_status'] = DetectionStatus.DS_POSITIVE
# Annotate the category, if it is unambiguous
if len(category_names) == 1:
im['_unambiguous_category'] = list(category_names)[0]
else:
raise Exception('Invalid detection state')
# ...for each image
return n_negative, n_positive, n_unknown, n_ambiguous
# ..._mark_detection_status()
def is_sas_url(s) -> bool:
"""
Placeholder for a more robust way to verify that a link is a SAS URL.
99.999% of the time this will suffice for what we're using it for right now.
:meta private:
"""
return (s.startswith(('http://', 'https://')) and ('core.windows.net' in s)
and ('?' in s))
def relative_sas_url(folder_url, relative_path):
"""
Given a container-level or folder-level SAS URL, create a SAS URL to the
specified relative path.
:meta private:
"""
relative_path = relative_path.replace('%','%25')
relative_path = relative_path.replace('#','%23')
relative_path = relative_path.replace(' ','%20')
if not is_sas_url(folder_url):
return None
tokens = folder_url.split('?')
assert len(tokens) == 2
if not tokens[0].endswith('/'):
tokens[0] = tokens[0] + '/'
if relative_path.startswith('/'):
relative_path = relative_path[1:]
return tokens[0] + relative_path + '?' + tokens[1]
def _render_bounding_boxes(
image_base_dir,
image_relative_path,
display_name,
detections,
res,
ground_truth_boxes=None,
detection_categories=None,
classification_categories=None,
options=None):
"""
Renders detection bounding boxes on a single image.
This is an internal function; if you want tools for rendering boxes on images, see
visualization.visualization_utils.
The source image is:
image_base_dir / image_relative_path
The target image is, for example:
[options.output_dir] /
['detections' or 'non_detections'] /
[filename with slashes turned into tildes]
"res" is a result type, e.g. "detections", "non-detections"; this determines the
output folder for the rendered image.
Only very preliminary support is provided for ground truth box rendering.
Returns the html info struct for this image in the format that's used for
write_html_image_list.
:meta private:
"""
if options is None:
options = PostProcessingOptions()
# Leaving code in place for reading from blob storage, may support this
# in the future.
"""
stream = io.BytesIO()
_ = blob_service.get_blob_to_stream(container_name, image_id, stream)
# resize is to display them in this notebook or in the HTML more quickly
image = Image.open(stream).resize(viz_size)
"""
image_full_path = None
if res in options.rendering_bypass_sets:
sample_name = res + '_' + path_utils.flatten_path(image_relative_path)
else:
if is_sas_url(image_base_dir):
image_full_path = relative_sas_url(image_base_dir, image_relative_path)
else:
image_full_path = os.path.join(image_base_dir, image_relative_path)
# os.path.isfile() is slow when mounting remote directories; much faster
# to just try/except on the image open.
try:
image = vis_utils.open_image(image_full_path)
except:
print('Warning: could not open image file {}'.format(image_full_path))
image = None
# return ''
# Render images to a flat folder
sample_name = res + '_' + path_utils.flatten_path(image_relative_path)
fullpath = os.path.join(options.output_dir, res, sample_name)
if image is not None:
original_size = image.size
if options.viz_target_width is not None:
image = vis_utils.resize_image(image, options.viz_target_width)
if ground_truth_boxes is not None and len(ground_truth_boxes) > 0:
# Create class labels like "gt_1" or "gt_27"
gt_classes = [0] * len(ground_truth_boxes)
label_map = {0:'ground truth'}
# for i_box,box in enumerate(ground_truth_boxes):
# gt_classes.append('_' + str(box[-1]))
vis_utils.render_db_bounding_boxes(ground_truth_boxes, gt_classes, image,
original_size=original_size,label_map=label_map,
thickness=4,expansion=4)
# render_detection_bounding_boxes expects either a float or a dict mapping
# category IDs to names.
if isinstance(options.confidence_threshold,float):
rendering_confidence_threshold = options.confidence_threshold
else:
category_ids = set()
for d in detections:
category_ids.add(d['category'])
rendering_confidence_threshold = {}
for category_id in category_ids:
rendering_confidence_threshold[category_id] = \
_get_threshold_for_category_id(category_id, options, detection_categories)
vis_utils.render_detection_bounding_boxes(
detections, image,
label_map=detection_categories,
classification_label_map=classification_categories,
confidence_threshold=rendering_confidence_threshold,
thickness=options.line_thickness,
expansion=options.box_expansion)
try:
image.save(fullpath)
except OSError as e:
# errno.ENAMETOOLONG doesn't get thrown properly on Windows, so
# we awkwardly check against a hard-coded limit
if (e.errno == errno.ENAMETOOLONG) or (len(fullpath) >= 259):
extension = os.path.splitext(sample_name)[1]
sample_name = res + '_' + str(uuid.uuid4()) + extension
image.save(os.path.join(options.output_dir, res, sample_name))
else:
raise
# Use slashes regardless of os
file_name = '{}/{}'.format(res,sample_name)
info = {
'filename': file_name,
'title': display_name,
'textStyle':\
'font-family:verdana,arial,calibri;font-size:80%;text-align:left;margin-top:20;margin-bottom:5'
}
# Optionally add links back to the original images
if options.link_images_to_originals and (image_full_path is not None):
# Handling special characters in links has been pushed down into
# write_html_image_list
#
# link_target = image_full_path.replace('\\','/')
# link_target = urllib.parse.quote(link_target)
link_target = image_full_path
info['linkTarget'] = link_target
return info
# ..._render_bounding_boxes
def _prepare_html_subpages(images_html, output_dir, options=None):
"""
Write out a series of html image lists, e.g. the "detections" or "non-detections"
pages.
image_html is a dictionary mapping an html page name (e.g. "detections_animal") to
a list of image structs friendly to write_html_image_list.
Returns a dictionary mapping category names to image counts.
"""
if options is None:
options = PostProcessingOptions()
# Count items in each category
image_counts = {}
for res, array in images_html.items():
image_counts[res] = len(array)
# Optionally sort by filename before writing to html
if options.html_sort_order == 'filename':
images_html_sorted = {}
for res, array in images_html.items():
sorted_array = sorted(array, key=lambda x: x['filename'])
images_html_sorted[res] = sorted_array
images_html = images_html_sorted
# Optionally sort by confidence before writing to html
elif options.html_sort_order == 'confidence':
images_html_sorted = {}
for res, array in images_html.items():
if not all(['max_conf' in d for d in array]):
print("Warning: some elements in the {} page don't have confidence values, can't sort by confidence".format(res))
else:
sorted_array = sorted(array, key=lambda x: x['max_conf'], reverse=True)
images_html_sorted[res] = sorted_array
images_html = images_html_sorted
else:
assert options.html_sort_order == 'random',\
'Unrecognized sort order {}'.format(options.html_sort_order)
images_html_sorted = {}
for res, array in images_html.items():
sorted_array = random.sample(array,len(array))
images_html_sorted[res] = sorted_array
images_html = images_html_sorted
# Write the individual HTML files
for res, array in images_html.items():
html_image_list_options = {}
html_image_list_options['maxFiguresPerHtmlFile'] = options.max_figures_per_html_file
html_image_list_options['headerHtml'] = '<h1>{}</h1>'.format(res.upper())
html_image_list_options['pageTitle'] = '{}'.format(res.lower())
# Don't write empty pages
if len(array) == 0:
continue
else:
write_html_image_list(
filename=os.path.join(output_dir, '{}.html'.format(res)),
images=array,
options=html_image_list_options)
return image_counts
# ..._prepare_html_subpages()
def _get_threshold_for_category_name(category_name,options):
"""
Determines the confidence threshold we should use for a specific category name.
"""
if isinstance(options.confidence_threshold,float):
return options.confidence_threshold
else:
assert isinstance(options.confidence_threshold,dict), \
'confidence_threshold must either be a float or a dict'
if category_name in options.confidence_threshold:
return options.confidence_threshold[category_name]
else:
assert 'default' in options.confidence_threshold, \
'category {} not in confidence_threshold dict, and no default supplied'.format(
category_name)
return options.confidence_threshold['default']
def _get_threshold_for_category_id(category_id,options,detection_categories):
"""
Determines the confidence threshold we should use for a specific category ID.
[detection_categories] is a dict mapping category IDs to names.
"""
if isinstance(options.confidence_threshold,float):
return options.confidence_threshold
assert category_id in detection_categories, \
'Invalid category ID {}'.format(category_id)
category_name = detection_categories[category_id]
return _get_threshold_for_category_name(category_name,options)
def _get_positive_categories(detections,options,detection_categories):
"""
Gets a sorted list of unique categories (as string IDs) above the threshold for this image
[detection_categories] is a dict mapping category IDs to names.
"""
positive_categories = set()
for d in detections:
threshold = _get_threshold_for_category_id(d['category'], options, detection_categories)
if d['conf'] >= threshold:
positive_categories.add(d['category'])
return sorted(positive_categories)
def _has_positive_detection(detections,options,detection_categories):
"""
Determines whether any positive detections are present in the detection list
[detections].
"""
found_positive_detection = False
for d in detections:
threshold = _get_threshold_for_category_id(d['category'], options, detection_categories)
if d['conf'] >= threshold:
found_positive_detection = True
break
return found_positive_detection
def _render_image_no_gt(file_info,detection_categories_to_results_name,
detection_categories,classification_categories,
options):
"""
Renders an image (with no ground truth information)
Returns a list of rendering structs, where the first item is a category (e.g. "detections_animal"),
and the second is a dict of information needed for rendering. E.g.:
[['detections_animal',
{
'filename': 'detections_animal/detections_animal_blah~01060415.JPG',
'title': '<b>Result type</b>: detections_animal,
<b>Image</b>: blah\\01060415.JPG,
<b>Max conf</b>: 0.897',
'textStyle': 'font-family:verdana,arial,calibri;font-size:80%;text-align:left;margin-top:20;margin-bottom:5',
'linkTarget': 'full_path_to_%5C01060415.JPG'
}]]
When no classification data is present, this list will always be length-1. When
classification data is present, an image may appear in multiple categories.
Populates the 'max_conf' field of the first element of the list.
Returns None if there are any errors.
"""
image_relative_path = file_info[0]
max_conf = file_info[1]
detections = file_info[2]
# Determine whether any positive detections are present (using a threshold that
# may vary by category)
found_positive_detection = _has_positive_detection(detections,options,detection_categories)
detection_status = DetectionStatus.DS_UNASSIGNED
if found_positive_detection:
detection_status = DetectionStatus.DS_POSITIVE
else:
if options.include_almost_detections:
if max_conf >= options.almost_detection_confidence_threshold:
detection_status = DetectionStatus.DS_ALMOST
else:
detection_status = DetectionStatus.DS_NEGATIVE
else:
detection_status = DetectionStatus.DS_NEGATIVE
if detection_status == DetectionStatus.DS_POSITIVE:
if options.separate_detections_by_category:
positive_categories = tuple(_get_positive_categories(detections,options,detection_categories))
if positive_categories not in detection_categories_to_results_name:
raise ValueError('Error: {} not in category mapping (file {})'.format(
str(positive_categories),image_relative_path))
res = detection_categories_to_results_name[positive_categories]
else:
res = 'detections'
elif detection_status == DetectionStatus.DS_NEGATIVE:
res = 'non_detections'
else:
assert detection_status == DetectionStatus.DS_ALMOST
res = 'almost_detections'
display_name = '<b>Result type</b>: {}, <b>Image</b>: {}, <b>Max conf</b>: {:0.3f}'.format(
res, image_relative_path, max_conf)
rendering_options = copy.copy(options)
if detection_status == DetectionStatus.DS_ALMOST:
rendering_options.confidence_threshold = \
rendering_options.almost_detection_confidence_threshold
rendered_image_html_info = _render_bounding_boxes(
image_base_dir=options.image_base_dir,
image_relative_path=image_relative_path,
display_name=display_name,
detections=detections,
res=res,
ground_truth_boxes=None,
detection_categories=detection_categories,
classification_categories=classification_categories,
options=rendering_options)
image_result = None
if len(rendered_image_html_info) > 0:
image_result = [[res, rendered_image_html_info]]
classes_rendered_this_image = set()
max_conf = 0
for det in detections:
if det['conf'] > max_conf:
max_conf = det['conf']
if ('classifications' in det) and (len(det['classifications']) > 0):
# This is a list of [class,confidence] pairs, sorted by confidence
classifications = det['classifications']
top1_class_id = classifications[0][0]
top1_class_name = classification_categories[top1_class_id]
top1_class_score = classifications[0][1]
# If we either don't have a confidence threshold, or we've met our
# confidence threshold
if (options.classification_confidence_threshold < 0) or \
(top1_class_score >= options.classification_confidence_threshold):
class_string = 'class_{}'.format(top1_class_name)
else:
class_string = 'class_unreliable'
if class_string not in classes_rendered_this_image:
image_result.append([class_string,
rendered_image_html_info])
classes_rendered_this_image.add(class_string)
# ...if this detection has classification info
# ...for each detection
image_result[0][1]['max_conf'] = max_conf
# ...if we got valid rendering info back from _render_bounding_boxes()
return image_result
# ...def _render_image_no_gt()
def _render_image_with_gt(file_info,ground_truth_indexed_db,
detection_categories,classification_categories,options):
"""
Render an image with ground truth information. See _render_image_no_gt for return
data format.
"""
image_relative_path = file_info[0]
max_conf = file_info[1]
detections = file_info[2]
# This should already have been normalized to either '/' or '\'
image_id = ground_truth_indexed_db.filename_to_id.get(image_relative_path, None)
if image_id is None:
print('Warning: couldn''t find ground truth for image {}'.format(image_relative_path))
return None
image = ground_truth_indexed_db.image_id_to_image[image_id]
annotations = ground_truth_indexed_db.image_id_to_annotations[image_id]
ground_truth_boxes = []
for ann in annotations:
if 'bbox' in ann:
ground_truth_box = [x for x in ann['bbox']]
ground_truth_box.append(ann['category_id'])
ground_truth_boxes.append(ground_truth_box)
gt_status = image['_detection_status']
gt_presence = bool(gt_status)
gt_classes = CameraTrapJsonUtils.annotations_to_class_names(
annotations, ground_truth_indexed_db.cat_id_to_name)
gt_class_summary = ','.join(gt_classes)
if gt_status > DetectionStatus.DS_MAX_DEFINITIVE_VALUE:
print(f'Skipping image {image_id}, does not have a definitive '
f'ground truth status (status: {gt_status}, classes: {gt_class_summary})')
return None
detected = _has_positive_detection(detections, options, detection_categories)
if gt_presence and detected:
if '_classification_accuracy' not in image.keys():
res = 'tp'
elif np.isclose(1, image['_classification_accuracy']):
res = 'tpc'
else:
res = 'tpi'
elif not gt_presence and detected:
res = 'fp'
elif gt_presence and not detected:
res = 'fn'
else:
res = 'tn'
display_name = '<b>Result type</b>: {}, <b>Presence</b>: {}, <b>Class</b>: {}, <b>Max conf</b>: {:0.3f}%, <b>Image</b>: {}'.format(
res.upper(), str(gt_presence), gt_class_summary,
max_conf * 100, image_relative_path)
rendered_image_html_info = _render_bounding_boxes(
image_base_dir=options.image_base_dir,
image_relative_path=image_relative_path,
display_name=display_name,
detections=detections,
res=res,
ground_truth_boxes=ground_truth_boxes,
detection_categories=detection_categories,
classification_categories=classification_categories,
options=options)
image_result = None
if len(rendered_image_html_info) > 0:
image_result = [[res, rendered_image_html_info]]
for gt_class in gt_classes:
image_result.append(['class_{}'.format(gt_class), rendered_image_html_info])
return image_result
# ...def _render_image_with_gt()
#%% Main function
def process_batch_results(options):
"""
Given a .json or .csv file containing MD results, do one or more of the following:
* Sample detections/non-detections and render to HTML (when ground truth isn't
available) (this is 99.9% of what this module is for)
* Evaluate detector precision/recall, optionally rendering results (requires
ground truth)
* Sample true/false positives/negatives and render to HTML (requires ground
truth)
Ground truth, if available, must be in COCO Camera Traps format:
https://github.com/agentmorris/MegaDetector/blob/main/megadetector/data_management/README.md#coco-camera-traps-format
Args:
options (PostProcessingOptions): everything we need to render a preview/analysis for
this set of results; see the PostProcessingOptions class for details.
Returns:
PostProcessingResults: information about the results/preview, most importantly the
HTML filename of the output. See the PostProcessingResults class for details.
"""
ppresults = PostProcessingResults()
##%% Expand some options for convenience
output_dir = options.output_dir
##%% Prepare output dir
os.makedirs(output_dir, exist_ok=True)
##%% Load ground truth if available
ground_truth_indexed_db = None
if (options.ground_truth_json_file is not None) and (len(options.ground_truth_json_file) > 0):
assert (options.confidence_threshold is None) or (isinstance(options.confidence_threshold,float)), \
'Variable confidence thresholds are not supported when supplying ground truth'
if (options.ground_truth_json_file is not None) and (len(options.ground_truth_json_file) > 0):
if options.separate_detections_by_category:
print("Warning: I don't know how to separate categories yet when doing " + \
"a P/R analysis, disabling category separation")
options.separate_detections_by_category = False
ground_truth_indexed_db = IndexedJsonDb(
options.ground_truth_json_file, b_normalize_paths=True,
filename_replacements=options.ground_truth_filename_replacements)
# Mark images in the ground truth as positive or negative
n_negative, n_positive, n_unknown, n_ambiguous = _mark_detection_status(
ground_truth_indexed_db, negative_classes=options.negative_classes,
unknown_classes=options.unlabeled_classes)
print(f'Finished loading and indexing ground truth: {n_negative} '
f'negative, {n_positive} positive, {n_unknown} unknown, '
f'{n_ambiguous} ambiguous')
if n_positive == 0:
print('\n*** Warning: no positives found in ground truth, analysis won\'t be very meaningful ***\n')
if n_negative == 0:
print('\n*** Warning: no negatives found in ground truth, analysis won\'t be very meaningful ***\n')
if n_ambiguous > 0:
print('\n*** Warning: {} images with ambiguous positive/negative status found in ground truth ***\n'.format(
n_ambiguous))
##%% Load detection (and possibly classification) results
# If the caller hasn't supplied results, load them
if options.api_detection_results is None:
detections_df, other_fields = load_api_results(
options.md_results_file, force_forward_slashes=True,
filename_replacements=options.api_output_filename_replacements)
ppresults.api_detection_results = detections_df
ppresults.api_other_fields = other_fields
else:
print('Bypassing detection results loading...')
assert options.api_other_fields is not None
detections_df = options.api_detection_results
other_fields = options.api_other_fields
# Determine confidence thresholds if necessary
if options.confidence_threshold is None:
options.confidence_threshold = \
get_typical_confidence_threshold_from_results(other_fields)
print('Choosing default confidence threshold of {} based on MD version'.format(
options.confidence_threshold))
if options.almost_detection_confidence_threshold is None and options.include_almost_detections:
assert isinstance(options.confidence_threshold,float), \
'If you are using a dictionary of confidence thresholds and almost-detections are enabled, ' + \
'you need to supply a threshold for almost detections.'
options.almost_detection_confidence_threshold = options.confidence_threshold - 0.05
if options.almost_detection_confidence_threshold < 0:
options.almost_detection_confidence_threshold = 0