From 16eeac46eeee2b7f3043a2a75ef01ebc7bd526a9 Mon Sep 17 00:00:00 2001 From: Dan Morris Date: Sat, 21 Nov 2026 12:27:58 -0800 Subject: [PATCH] cleaning up hard-coded category names --- TODO.md | 15 - megadetector/data_management/animl_to_md.py | 4 +- .../data_management/annotation_constants.py | 42 +- megadetector/data_management/zamba_to_md.py | 4 +- megadetector/detection/pytorch_detector.py | 38 +- megadetector/detection/rfdetr_detector.py | 72 +- megadetector/detection/run_detector.py | 637 +++++++++++++++++- megadetector/detection/run_detector_batch.py | 105 +-- .../run_inference_with_yolov5_val.py | 6 +- megadetector/detection/tf_detector.py | 19 +- .../postprocessing/convert_output_format.py | 2 +- megadetector/postprocessing/md_to_labelme.py | 3 +- megadetector/utils/wi_platform_utils.py | 2 +- megadetector/utils/wi_taxonomy_utils.py | 2 +- .../visualization/visualization_utils.py | 15 +- .../visualize_detector_output.py | 11 +- .../visualization/visualize_video_output.py | 10 +- 17 files changed, 804 insertions(+), 183 deletions(-) diff --git a/TODO.md b/TODO.md index e7a67b70..e8da3cf5 100644 --- a/TODO.md +++ b/TODO.md @@ -855,21 +855,6 @@ E3 !maintenance -## Address module-level globals in run_detector_batch and run_detector - -The DEFAULT_DETECTOR_LABEL_MAP module-level global variable in run_detector_batch is used to pass custom class mappings around; this is sloppy. write_results_to_file should receive optional an optional category map, rather than communicating this via a global variable. A good test case is RF-DETR/CFD support, which currently loads classes in a sensible way (in load_model()), then stashes them in a global variable. - -Similarly, the USE_MODEL_NATIVE_CLASSES module-level global in run_detector is used to pass a custom option around; this is also sloppy. - -Fix both of these. - -P0 - -E2 - -!maintenance - - ## Modern preprocessing with image queue in notebook manage_local_batch contains a check indicating that preprocess_on_image_queue is incompatible with "modern" compatibility mode, look for: diff --git a/megadetector/data_management/animl_to_md.py b/megadetector/data_management/animl_to_md.py index 666bb180..67381729 100644 --- a/megadetector/data_management/animl_to_md.py +++ b/megadetector/data_management/animl_to_md.py @@ -27,8 +27,8 @@ import pandas as pd from megadetector.utils.ct_utils import write_json -from megadetector.detection.run_detector import DEFAULT_DETECTOR_LABEL_MAP -detection_category_id_to_name = DEFAULT_DETECTOR_LABEL_MAP +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP +detection_category_id_to_name = dict(DEFAULT_DETECTOR_LABEL_MAP) #%% Main function diff --git a/megadetector/data_management/annotation_constants.py b/megadetector/data_management/annotation_constants.py index 19642e84..53c8da2e 100644 --- a/megadetector/data_management/annotation_constants.py +++ b/megadetector/data_management/annotation_constants.py @@ -2,32 +2,30 @@ annotation_constants.py -Defines default categories for MegaDetector output boxes. +Defines the default categories for MegaDetector output boxes. This is the one and only place +where these defaults are defined. -Used throughout the repo; do not change unless you are Dan or Siyu. In fact, do not change unless -you are both Dan *and* Siyu. +Models are not required to use these categories; detectors read their categories from the +model file where possible (see run_detector.get_detector_category_info()). But all publicly +released MegaDetector models use these categories, and things like box colors throughout this +repo assume that "animal" is category "1". -We use integer IDs here; this is different from the MD .json file format, -where indices are string integers. +Do not change unless you are Dan or Siyu. In fact, do not change unless you are both Dan *and* +Siyu. """ #%% Constants -# MegaDetector output categories (the "empty" category is implicit) -detector_bbox_categories = [ - {'id': 0, 'name': 'empty'}, - {'id': 1, 'name': 'animal'}, - {'id': 2, 'name': 'person'}, - {'id': 3, 'name': 'vehicle'} -] - -# This is used for choosing colors, so it ignores the "empty" class. -NUM_DETECTOR_CATEGORIES = len(detector_bbox_categories) - 1 - -detector_bbox_category_id_to_name = {} -detector_bbox_category_name_to_id = {} - -for cat in detector_bbox_categories: - detector_bbox_category_id_to_name[cat['id']] = cat['name'] - detector_bbox_category_name_to_id[cat['name']] = cat['id'] +#: Default MegaDetector output categories, in the format used for the "detection_categories" +#: field in the MD output format (string integer IDs mapped to names). Category "0" is +#: implicitly reserved for "empty", so these IDs start at 1. +DEFAULT_DETECTOR_LABEL_MAP = { + '1': 'animal', + '2': 'person', + '3': 'vehicle' +} + +#: Number of default detector categories; this is used for choosing colors (e.g., classification +#: categories are colored starting after the detector categories). +NUM_DETECTOR_CATEGORIES = len(DEFAULT_DETECTOR_LABEL_MAP) diff --git a/megadetector/data_management/zamba_to_md.py b/megadetector/data_management/zamba_to_md.py index ad373cd6..6376ddf7 100644 --- a/megadetector/data_management/zamba_to_md.py +++ b/megadetector/data_management/zamba_to_md.py @@ -40,7 +40,7 @@ from megadetector.utils.ct_utils import sort_dictionary_by_value from megadetector.utils.wi_taxonomy_utils import get_common_name_from_prediction_string from megadetector.utils.wi_taxonomy_utils import is_valid_prediction_string -from megadetector.detection.run_detector import DEFAULT_DETECTOR_LABEL_MAP +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP from megadetector.utils.path_utils import find_images from megadetector.visualization.visualization_utils import get_image_size @@ -180,7 +180,7 @@ def _zamba_image_results_to_md_results(df,output_file,image_folder): for detection_category_id in detection_category_ids: detection_category_id_to_name[detection_category_id] = detection_category_id else: - detection_category_id_to_name = DEFAULT_DETECTOR_LABEL_MAP + detection_category_id_to_name = dict(DEFAULT_DETECTOR_LABEL_MAP) filename_to_image = {} diff --git a/megadetector/detection/pytorch_detector.py b/megadetector/detection/pytorch_detector.py index 030b17b2..8940c1d6 100644 --- a/megadetector/detection/pytorch_detector.py +++ b/megadetector/detection/pytorch_detector.py @@ -25,6 +25,7 @@ from megadetector.detection.run_detector import \ CONF_DIGITS, COORD_DIGITS, FAILURE_INFER, FAILURE_IMAGE_OPEN, \ get_detector_version_from_model_file, \ + get_detector_category_info, \ known_models from megadetector.utils.ct_utils import parse_bool_string from megadetector.utils.ct_utils import is_running_in_gha @@ -759,15 +760,12 @@ def __init__(self, model_path, detector_options=None, verbose=False): # Parse options specific to this detector family force_cpu = False - use_model_native_classes = False compatibility_mode = default_compatibility_mode if detector_options is not None: if 'force_cpu' in detector_options: force_cpu = parse_bool_string(detector_options['force_cpu']) - if 'use_model_native_classes' in detector_options: - use_model_native_classes = parse_bool_string(detector_options['use_model_native_classes']) if 'compatibility_mode' in detector_options: if detector_options['compatibility_mode'] is None: compatibility_mode = default_compatibility_mode @@ -812,11 +810,15 @@ def __init__(self, model_path, detector_options=None, verbose=False): #: :meta private: self.printed_image_size_warning = False - #: If this is False, we assume the underlying model is producing class indices in the - #: set (0,1,2) (and we assert() on this), and we add 1 to get to the backwards-compatible - #: MD classes (1,2,3) before generating output. If this is True, we use whatever - #: indices the model provides - self.use_model_native_classes = use_model_native_classes + #: Maps string category IDs to category names, in the format used for the + #: 'detection_categories' field in MD output files; see + #: run_detector.get_detector_category_info(). None for preprocess-only instances. + self.detection_categories = None + + #: Value added to each class ID predicted by the model to get the corresponding key in + #: [detection_categories]; this is 1 for MegaDetector models, 0 for most other models. + #: None for preprocess-only instances. + self.category_id_offset = None #: This allows us to maintain backwards compatibility across a set of changes to the #: way this class does inference. Currently should start with either "default" or @@ -850,6 +852,13 @@ def __init__(self, model_path, detector_options=None, verbose=False): if preprocess_only: return + category_info = get_detector_category_info(model_path, detector_options=detector_options) + self.detection_categories = category_info['detection_categories'] + self.category_id_offset = category_info['category_id_offset'] + + print('Detection categories ({}): {}'.format( + category_info['category_source'], self.detection_categories)) + if (detector_options is not None) and \ ('device' in detector_options) and \ detector_options['device'] is not None: @@ -1402,15 +1411,14 @@ def _process_batch_group(self, group_items, results, detection_threshold, augmen api_box = ct_utils.round_float_array(api_box, precision=COORD_DIGITS) conf = ct_utils.round_float(conf.tolist(), precision=CONF_DIGITS) - if not self.use_model_native_classes: - cls = int(cls.tolist()) + 1 - if cls not in (1, 2, 3): - raise KeyError(f'{cls} is not a valid class.') - else: - cls = int(cls.tolist()) + category_id = str(int(cls.tolist()) + self.category_id_offset) + if category_id not in self.detection_categories: + raise KeyError('Model predicted category {}, which is not one of '.format( + category_id) + 'the categories for this detector ({})'.format( + ','.join(self.detection_categories.keys()))) detections.append({ - 'category': str(cls), + 'category': category_id, 'conf': conf, 'bbox': api_box }) diff --git a/megadetector/detection/rfdetr_detector.py b/megadetector/detection/rfdetr_detector.py index 7e525873..c81f10c3 100644 --- a/megadetector/detection/rfdetr_detector.py +++ b/megadetector/detection/rfdetr_detector.py @@ -37,6 +37,7 @@ import numpy as np from megadetector.detection.run_detector import CONF_DIGITS, COORD_DIGITS, FAILURE_INFER +from megadetector.detection.run_detector import get_detector_category_info from megadetector.utils.ct_utils import round_float, round_float_array from megadetector.utils.ct_utils import parse_bool_string @@ -165,7 +166,6 @@ def load_model(detector_file, - 'model': the loaded RF-DETR model - 'model_type' (str): model type name (e.g. 'RFDETRSmall') - 'image_size' (int): inference resolution - - 'detection_categories' (dict): mapping from string category IDs to class names """ assert dtype in dtype_string_to_torch_dtype, \ @@ -247,24 +247,11 @@ def load_model(detector_file, # ...with TF32ExecutionContext(...) - # Get class names from model - # - # model.class_names is a list of strings. Note to self: in older rfdetr versions, it was - # a dict mapping 1-indexed class IDs to names. - class_names = model.class_names - print('Class names: {}'.format(class_names)) - - # Build detection_categories dict - detection_categories = {} - for i_class,class_name in enumerate(class_names): - detection_categories[str(i_class)] = class_name - return \ { 'model': model, 'model_type': model_type, - 'image_size': image_size, - 'detection_categories': detection_categories + 'image_size': image_size } # ...def load_model(...) @@ -272,7 +259,11 @@ def load_model(detector_file, #%% Detection format conversion -def convert_detections_to_md_format(detections, image_width, image_height): +def convert_detections_to_md_format(detections, + image_width, + image_height, + category_id_offset=0, + detection_categories=None): """ Convert RF-DETR/Supervision detections to MegaDetector format. @@ -280,6 +271,11 @@ def convert_detections_to_md_format(detections, image_width, image_height): detections: supervision Detections object with xyxy, confidence, class_id image_width (int): image width in pixels image_height (int): image height in pixels + category_id_offset (int, optional): value to add to each class ID predicted by the + model to get the output category ID + detection_categories (dict, optional): the valid output category IDs (string IDs mapped + to names); if this is not None, raises an error if the model predicts a category that + is not in this dict Returns: list: list of detection dicts in MegaDetector format @@ -313,7 +309,12 @@ def convert_detections_to_md_format(detections, image_width, image_height): # RF-DETR class_ids are 0-indexed when returned from the API class_id = int(detections.class_id[i_detection]) - category = str(class_id) + category = str(class_id + category_id_offset) + + if (detection_categories is not None) and (category not in detection_categories): + raise KeyError('Model predicted category {}, which is not one of '.format( + category) + 'the categories for this detector ({})'.format( + ','.join(detection_categories.keys()))) bbox = round_float_array([x_min_norm, y_min_norm, width_norm, height_norm], precision=COORD_DIGITS) @@ -401,9 +402,16 @@ def __init__(self, model_path, detector_options=None, verbose=False): #: The resolved variant class name (e.g. 'RFDETRNano'); None until the model is loaded self.model_type = None - #: Mapping from string category IDs to class names; None until the model is loaded + #: Maps string category IDs to category names, in the format used for the + #: 'detection_categories' field in MD output files; see + #: run_detector.get_detector_category_info(). None until the model is loaded. self.detection_categories = None + #: Value added to each class ID predicted by the model to get the corresponding key in + #: [detection_categories]; this is 1 for MegaDetector models, 0 for most other models. + #: None until the model is loaded. + self.category_id_offset = None + #: The exact batch size this model requires at inference time, or None if any batch #: size is allowed. This is only set when the model has been compiled, since #: compilation (torch.jit.trace) ties the model to a single batch size. @@ -482,7 +490,13 @@ def __init__(self, model_path, detector_options=None, verbose=False): self.model = model_info['model'] self.model_type = model_info['model_type'] self.image_size = model_info['image_size'] - self.detection_categories = model_info['detection_categories'] + + category_info = get_detector_category_info(model_path, detector_options=detector_options) + self.detection_categories = category_info['detection_categories'] + self.category_id_offset = category_info['category_id_offset'] + + print('Detection categories ({}): {}'.format( + category_info['category_source'], self.detection_categories)) # A compiled model can only be run at the batch size it was compiled for, so record # that batch size; generate_detections_one_batch() pads short batches accordingly. @@ -716,7 +730,25 @@ def generate_detections_one_batch(self, image_width, image_height = image_shapes[i_img] - md_detections = convert_detections_to_md_format(detections, image_width, image_height) + # This will fail if the model predicts a category that is not in + # self.detection_categories; mark that image as failed, consistent with + # the behavior of PTDetector. + try: + md_detections = convert_detections_to_md_format( + detections, + image_width, + image_height, + category_id_offset=self.category_id_offset, + detection_categories=self.detection_categories) + except Exception as e: + print('Warning: could not convert detections for image {}: {}'.format( + image_ids[i_img], str(e))) + results.append({ + 'file': image_ids[i_img], + 'detections': None, + 'failure': FAILURE_INFER + ': ' + str(e) + }) + continue max_conf = 0.0 for det in md_detections: diff --git a/megadetector/detection/run_detector.py b/megadetector/detection/run_detector.py index 7a4d296a..d951d9f5 100644 --- a/megadetector/detection/run_detector.py +++ b/megadetector/detection/run_detector.py @@ -43,6 +43,7 @@ from megadetector.utils.url_utils import download_url from megadetector.utils.ct_utils import parse_kvp_list from megadetector.utils.path_utils import compute_file_hash +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP # ignoring all "PIL cannot read EXIF metainfo for the images" warnings warnings.filterwarnings('ignore', '(Possibly )?corrupt EXIF data', UserWarning) @@ -61,24 +62,12 @@ CONF_DIGITS = 3 COORD_DIGITS = 4 -# Label mapping for MegaDetector -DEFAULT_DETECTOR_LABEL_MAP = { - '1': 'animal', - '2': 'person', - '3': 'vehicle' # available in megadetector v4+ -} - -# Should we allow classes that don't look anything like the MegaDetector classes? -# -# This flag needs to get set if you want to, for example, run an off-the-shelf -# YOLO model with this package. -# -# By default, we error if we see unfamiliar classes. -# -# TODO: the use of a global variable to manage this was fine when this was really -# experimental, but this is really sloppy now that we actually use this code for -# models other than MegaDetector. -USE_MODEL_NATIVE_CLASSES = False +# All publicly released MegaDetector models store exactly these class names, with zero-indexed +# integer class IDs ({0: 'animal', 1: 'person', 2: 'vehicle'}), i.e. the default MD categories +# minus one. When a model file contains exactly these names and IDs, we add 1 to every class ID +# at inference time, to produce the default MD categories. See get_detector_category_info(). +MEGADETECTOR_MODEL_CLASS_NAMES = \ + {(int(k) - 1): v for k, v in DEFAULT_DETECTOR_LABEL_MAP.items()} # Detection threshold to recommend to callers when all other mechanisms for choosing # a model-specific threshold fail @@ -654,7 +643,6 @@ def load_detector(model_file, force_cpu,detector_options['force_cpu'])) else: detector_options['force_cpu'] = force_cpu - detector_options['use_model_native_classes'] = USE_MODEL_NATIVE_CLASSES detector = PTDetector(model_file, detector_options, verbose=verbose) elif model_file.endswith('.pth'): @@ -667,10 +655,6 @@ def load_detector(model_file, detector_options = {} detector = RFDETRDetector(model_file, detector_options, verbose=verbose) - # This is a hack - global DEFAULT_DETECTOR_LABEL_MAP - DEFAULT_DETECTOR_LABEL_MAP = detector.detection_categories - else: raise ValueError('Unrecognized model format: {}'.format(model_file)) @@ -685,6 +669,427 @@ def load_detector(model_file, # ...def load_detector(...) +#%% Detector category functions + +# When reading class names from a model file, we unpickle the file without importing any +# model code (e.g. YOLOv5, ultralytics), replacing every class that isn't from one of these +# modules with a stub class that just stores its pickled state. The stub approach works +# regardless of which (if any) YOLO libraries are installed, and doesn't execute model code. +_modules_allowed_when_reading_model_metadata = \ + ('torch', 'collections', 'builtins', 'numpy', 'copyreg', '_codecs') + + +class _StubObject: + """ + Stand-in for classes that we don't import when reading metadata from a model file. Instances + just store whatever state was pickled. See _load_model_file_without_model_code(). + """ + + def __init__(self, *args, **kwargs): + """ + Ignores all constructor arguments. + """ + + pass + + def __setstate__(self, state): + """ + Stores pickled state as attributes, where possible. + """ + + # Objects with __slots__ pickle their state as a (dict, dict) tuple + if isinstance(state, tuple) and (len(state) == 2) and \ + ((state[0] is None) or isinstance(state[0], dict)) and \ + ((state[1] is None) or isinstance(state[1], dict)): + for d in state: + if d is not None: + self.__dict__.update(d) + elif isinstance(state, dict): + self.__dict__.update(state) + else: + self.__dict__['_stub_state'] = state + + def __call__(self, *args, **kwargs): + """ + Some pickled objects are reconstructed by calling functions that return types (e.g. + dill's _load_type()), which we've replaced with stubs; the "types" those stubs return + are stub instances, which then get called to create objects. + """ + + return _StubObject() + + # Subclasses of list and dict get populated via append/extend/__setitem__ during unpickling + + def append(self, item): + """ + Supports unpickling of list subclasses. + """ + + self.__dict__.setdefault('_stub_items', []).append(item) + + def extend(self, items): + """ + Supports unpickling of list subclasses. + """ + + self.__dict__.setdefault('_stub_items', []).extend(items) + + def __setitem__(self, key, value): + """ + Supports unpickling of dict subclasses. + """ + + self.__dict__.setdefault('_stub_dict', {})[key] = value + +# ...class _StubObject + + +def _load_model_file_without_model_code(model_file): + """ + Loads a PyTorch model file (.pt or .pth) without importing the code that defines the model, + replacing all model classes with instances of _StubObject. Tensors are loaded normally (on + the CPU). + + Args: + model_file (str): the model file to load + + Returns: + object: whatever torch.load() returns for this file, typically a dict, with stubs in place + of model objects + """ + + import pickle + import types + import torch + + stub_classes = {} + + class _StubUnpickler(pickle.Unpickler): + + def find_class(self, module, name): + if module.split('.')[0] in _modules_allowed_when_reading_model_metadata: + return super().find_class(module, name) + key = module + '.' + name + if key not in stub_classes: + stub_classes[key] = type(name, (_StubObject,), {'__module__': 'stub.' + module}) + return stub_classes[key] + + def _stub_load(f, **kwargs): + return _StubUnpickler(f, **kwargs).load() + + stub_pickle_module = types.ModuleType('stub_pickle') + stub_pickle_module.Unpickler = _StubUnpickler + stub_pickle_module.load = _stub_load + + try: + checkpoint = torch.load(model_file, map_location='cpu', weights_only=False, + pickle_module=stub_pickle_module) + # For a transitional period, we want to support torch 1.1x, where the weights_only + # parameter doesn't exist + except Exception as e: + if "'weights_only' is an invalid keyword" in str(e): + checkpoint = torch.load(model_file, map_location='cpu', + pickle_module=stub_pickle_module) + else: + raise + + return checkpoint + +# ...def _load_model_file_without_model_code(...) + + +def _normalize_class_names(class_names): + """ + Converts class names in any of the formats we find in model files (a list of names, a + single name, or a dict mapping int or int-string IDs to names) to a dict mapping int + IDs to string names. + + Args: + class_names (list, str, or dict): class names in any supported format + + Returns: + dict: dict mapping int IDs to names, or None if [class_names] is None or empty + """ + + if class_names is None: + return None + + if isinstance(class_names, str): + class_names = [class_names] + + if isinstance(class_names, (list, tuple)): + class_names_dict = {} + for i_class, class_name in enumerate(class_names): + class_names_dict[i_class] = class_name + class_names = class_names_dict + + if not isinstance(class_names, dict): + raise ValueError('Unrecognized class name format: {}'.format(type(class_names))) + + if len(class_names) == 0: + return None + + normalized_class_names = {} + for class_id, class_name in class_names.items(): + try: + class_id = int(class_id) + except Exception: + raise ValueError('Illegal (non-integer) class ID in model file: {}'.format(class_id)) + assert class_id >= 0, 'Illegal (negative) class ID in model file: {}'.format(class_id) + normalized_class_names[class_id] = str(class_name) + + return normalized_class_names + +# ...def _normalize_class_names(...) + + +def _read_class_names_from_yolo_checkpoint(checkpoint): + """ + Finds class names in a checkpoint loaded from a YOLO-family (YOLOv5, YOLOv9, ultralytics) + .pt file. + + Args: + checkpoint (object): checkpoint loaded via _load_model_file_without_model_code() + + Returns: + tuple: (class_names, num_classes), where class_names is a dict mapping int IDs to names + (or None if no class names are available), and num_classes is the number of classes (or + None if we can't determine the number of classes) + """ + + # Models are typically in checkpoint['model']; un-stripped ultralytics checkpoints (e.g. + # last.pt during training) store None in checkpoint['model'], and store the model only in + # checkpoint['ema']. + candidate_models = [] + if isinstance(checkpoint, dict): + for key in ('model', 'ema'): + if checkpoint.get(key, None) is not None: + candidate_models.append(checkpoint[key]) + else: + candidate_models.append(checkpoint) + + # Names are typically in model.names, either as a list (older YOLOv5 versions) or a dict + # (newer YOLOv5 versions, YOLOv9, ultralytics). Also check model.yaml['names'], which is + # occasionally populated. + for model in candidate_models: + class_names = getattr(model, 'names', None) + model_yaml = getattr(model, 'yaml', None) + if (class_names is None) and isinstance(model_yaml, dict): + class_names = model_yaml.get('names', None) + class_names = _normalize_class_names(class_names) + if class_names is not None: + return class_names, len(class_names) + + # If we didn't find names, see whether we can at least determine the number of classes + for model in candidate_models: + num_classes = getattr(model, 'nc', None) + model_yaml = getattr(model, 'yaml', None) + if (num_classes is None) and isinstance(model_yaml, dict): + num_classes = model_yaml.get('nc', None) + if num_classes is None: + # The detection head is the last layer + try: + num_classes = model.model[-1].nc + except Exception: + pass + if num_classes is not None: + return None, int(num_classes) + + return None, None + +# ...def _read_class_names_from_yolo_checkpoint(...) + + +def _read_class_names_from_rfdetr_checkpoint(checkpoint): + """ + Finds class names in a checkpoint loaded from an RF-DETR .pth file. + + Args: + checkpoint (dict): checkpoint loaded via _load_model_file_without_model_code() + + Returns: + tuple: (class_names, num_classes), where class_names is a dict mapping int IDs to names + (or None if no class names are available), and num_classes is the number of classes (or + None if we can't determine the number of classes) + """ + + assert isinstance(checkpoint, dict), 'Unrecognized RF-DETR checkpoint format' + + # The rfdetr package stores class names in checkpoint['args'].class_names (args may be + # a dict or an argparse.Namespace); PyTorch Lightning-format checkpoints store them in + # checkpoint['hyper_parameters'] instead. + for key in ('args', 'hyper_parameters'): + args = checkpoint.get(key, None) + if args is None: + continue + if isinstance(args, dict): + class_names = args.get('class_names', None) + else: + class_names = getattr(args, 'class_names', None) + class_names = _normalize_class_names(class_names) + if class_names is not None: + return class_names, len(class_names) + + # If we didn't find names, determine the number of classes from the size of the + # classification head, which has one output per possible class ID. + for key in ('model', 'state_dict'): + state_dict = checkpoint.get(key, None) + if not isinstance(state_dict, dict): + continue + for tensor_name in state_dict.keys(): + if tensor_name.endswith('class_embed.bias') and \ + (not tensor_name.endswith('enc_out_class_embed.bias')): + return None, int(state_dict[tensor_name].shape[0]) + + return None, None + +# ...def _read_class_names_from_rfdetr_checkpoint(...) + + +def _class_names_to_category_info(class_names, num_classes=None): + """ + Converts class names read from a model file to MD-formatted detection categories, applying + the MegaDetector category ID offset if appropriate. + + Args: + class_names (dict): dict mapping int class IDs (as produced by the model) to names, or + None if no names are available + num_classes (int, optional): number of classes, only used if [class_names] is None, in + which case we generate names like "category_00", "category_01", etc. + + Returns: + dict: a dict with fields 'detection_categories' and 'category_id_offset'; see + get_detector_category_info() + """ + + # If we don't have class names, generate names like "category_00" + if class_names is None: + + assert (num_classes is not None) and (num_classes > 0), \ + 'Cannot generate category names without a class count' + n_digits = max(2, len(str(num_classes - 1))) + detection_categories = {} + for class_id in range(0, num_classes): + detection_categories[str(class_id)] = 'category_' + str(class_id).zfill(n_digits) + return {'detection_categories': detection_categories, 'category_id_offset': 0} + + # If these are exactly the MegaDetector classes, offset the class IDs to produce the + # default MD categories (1=animal, 2=person, 3=vehicle) + if class_names == MEGADETECTOR_MODEL_CLASS_NAMES: + return {'detection_categories': dict(DEFAULT_DETECTOR_LABEL_MAP), 'category_id_offset': 1} + + # Otherwise use the model's class IDs as they are + detection_categories = {} + for class_id in sorted(class_names.keys()): + detection_categories[str(class_id)] = class_names[class_id] + return {'detection_categories': detection_categories, 'category_id_offset': 0} + +# ...def _class_names_to_category_info(...) + + +def get_detector_category_info(model_file, detector_options=None): + """ + Determines the detection categories that a detector will produce, and how class IDs + predicted by the model map to those categories. This reads only the model file (it + doesn't load the model), so it can be used, e.g., to write results in a process that + didn't run the model. + + Categories are determined as follows: + + - If detector_options['class_mapping_filename'] is present, categories are read from that + file (see read_classes_from_yolo_dataset_file() for supported formats), and class IDs + are used exactly as the model produces them. + - TensorFlow (.pb) models use the default MD categories (MDv4 produces 1-indexed class IDs). + - For PyTorch models (YOLO .pt files, RF-DETR .pth files), class names are read from the + model file. If the class names are exactly the MegaDetector class names with zero-indexed + IDs ({0: 'animal', 1: 'person', 2: 'vehicle'}), class IDs are offset by 1 to produce the + default MD categories. Otherwise, class IDs are used exactly as the model produces them. + If the model file doesn't contain class names, we generate names like "category_00". + + Args: + model_file (str): model filename (e.g. c:/x/z/md_v5a.0.0.pt) or known model name (e.g. + "MDV5A"), which will be downloaded if necessary + detector_options (dict, optional): key/value pairs that are interpreted differently + by different detectors; the only option used here is 'class_mapping_filename' + + Returns: + dict: a dict with fields: + - 'detection_categories' (dict): maps string category IDs to category names, in the + format used for the 'detection_categories' field in MD output files + - 'category_id_offset' (int): the value to add to a class ID predicted by the model + to get the corresponding category ID in 'detection_categories' + - 'category_source' (str): a human-readable description of where the categories + came from + """ + + if isinstance(detector_options, str): + detector_options = parse_kvp_list(detector_options.split(',')) + elif isinstance(detector_options, list): + detector_options = parse_kvp_list(detector_options) + + # If the caller supplied a class mapping file, that takes precedence over the model file + if (detector_options is not None) and \ + (detector_options.get('class_mapping_filename', None) is not None): + + # This is imported here, rather than at module scope, to avoid a circular import + from megadetector.data_management.yolo_output_to_md_output import \ + read_classes_from_yolo_dataset_file + + class_mapping_filename = detector_options['class_mapping_filename'] + class_mapping = read_classes_from_yolo_dataset_file(class_mapping_filename) + detection_categories = {} + for class_id in sorted(class_mapping.keys()): + detection_categories[str(class_id)] = class_mapping[class_id] + return {'detection_categories': detection_categories, + 'category_id_offset': 0, + 'category_source': 'class mapping file {}'.format(class_mapping_filename)} + + model_file = try_download_known_detector(model_file) + + if not os.path.isfile(model_file): + raise FileNotFoundError('Model file {} does not exist'.format(model_file)) + + if model_file.endswith('.pb'): + + # TensorFlow MegaDetector models (MDv4 and earlier) don't store class names, and produce + # 1-indexed class IDs. + return {'detection_categories': dict(DEFAULT_DETECTOR_LABEL_MAP), + 'category_id_offset': 0, + 'category_source': 'default MegaDetector categories (TensorFlow model)'} + + elif model_file.endswith('.pt') or model_file.endswith('.pth'): + + checkpoint = _load_model_file_without_model_code(model_file) + if model_file.endswith('.pt'): + class_names, num_classes = _read_class_names_from_yolo_checkpoint(checkpoint) + else: + class_names, num_classes = _read_class_names_from_rfdetr_checkpoint(checkpoint) + del checkpoint + + if (class_names is None) and (num_classes is None): + raise ValueError('Could not determine the classes for model file {}; consider '.format( + model_file) + 'supplying a class mapping file') + + category_info = _class_names_to_category_info(class_names, num_classes) + if class_names is None: + category_info['category_source'] = \ + 'generated names (model file contains {} classes, but no class names)'.format( + num_classes) + elif category_info['category_id_offset'] == 0: + category_info['category_source'] = 'class names from model file' + else: + category_info['category_source'] = \ + 'MegaDetector class names from model file, class IDs offset by {}'.format( + category_info['category_id_offset']) + return category_info + + else: + + raise ValueError('Unrecognized model format: {}'.format(model_file)) + +# ...def get_detector_category_info(...) + + #%% Main function def load_and_run_detector(model_file, @@ -873,7 +1278,7 @@ def input_file_to_detection_file(fn, crop_index=-1): # Image is modified in place vis_utils.render_detection_bounding_boxes(result['detections'], image, - label_map=DEFAULT_DETECTOR_LABEL_MAP, + label_map=detector.detection_categories, confidence_threshold=render_confidence_threshold, thickness=box_thickness, expansion=box_expansion, label_font_size=label_font_size, @@ -1318,3 +1723,187 @@ def main(): # noqa output_dir=output_dir, render_confidence_threshold=render_confidence_threshold, crop_images=crop_images) + + +#%% Tests + +def test_class_names_to_category_info(): + """ + Tests the mapping from class names (as read from a model file) to detection categories. + """ + + # Exactly the MegaDetector classes: offset by 1 + info = _class_names_to_category_info(_normalize_class_names(['animal', 'person', 'vehicle'])) + assert info['detection_categories'] == DEFAULT_DETECTOR_LABEL_MAP, 'MD categories mismatch' + assert info['category_id_offset'] == 1, 'MD categories should be offset by 1' + + # Dicts with int or int-string keys are equivalent to lists + info = _class_names_to_category_info( + _normalize_class_names({'0': 'animal', '1': 'person', '2': 'vehicle'})) + assert info['detection_categories'] == DEFAULT_DETECTOR_LABEL_MAP, 'MD categories mismatch' + assert info['category_id_offset'] == 1, 'MD categories should be offset by 1' + + # The returned categories should be a copy of the defaults, not the defaults themselves + assert info['detection_categories'] is not DEFAULT_DETECTOR_LABEL_MAP, \ + 'Default categories should be copied' + + # Anything other than exactly the MD classes and IDs: no offset + for class_names in (['fish'], + ['person', 'animal', 'vehicle'], + ['animal', 'person', 'vehicle', 'boat'], + ['Animal', 'Person', 'Vehicle'], + {1: 'animal', 2: 'person', 3: 'vehicle'}): + normalized_class_names = _normalize_class_names(class_names) + info = _class_names_to_category_info(normalized_class_names) + assert info['category_id_offset'] == 0, \ + 'Unexpected offset for {}'.format(str(class_names)) + expected_categories = {str(k): v for k, v in normalized_class_names.items()} + assert info['detection_categories'] == expected_categories, \ + 'Unexpected categories for {}'.format(str(class_names)) + + # Names that look like IDs are used as provided + info = _class_names_to_category_info(_normalize_class_names({0: '0', 1: '1'})) + assert info['detection_categories'] == {'0': '0', '1': '1'}, 'Numeric names mismatch' + + # No names: generate names + info = _class_names_to_category_info(None, num_classes=3) + assert info['detection_categories'] == \ + {'0': 'category_00', '1': 'category_01', '2': 'category_02'}, 'Generated names mismatch' + assert info['category_id_offset'] == 0, 'Generated names should not be offset' + + info = _class_names_to_category_info(None, num_classes=120) + assert info['detection_categories']['0'] == 'category_000', 'Generated name width mismatch' + assert info['detection_categories']['119'] == 'category_119', 'Generated name width mismatch' + + assert _normalize_class_names(None) is None, 'None names should normalize to None' + assert _normalize_class_names([]) is None, 'Empty names should normalize to None' + assert _normalize_class_names('fish') == {0: 'fish'}, 'Single name normalization mismatch' + +# ...def test_class_names_to_category_info(...) + + +def test_get_detector_category_info(): + """ + Tests reading detection categories from (synthetic) model files. + """ + + import shutil + import types + import torch + from megadetector.utils.ct_utils import make_test_folder + + test_folder = make_test_folder(subfolder='detector_category_tests') + + try: + + def _write_model_file(fn, checkpoint): + fn = os.path.join(test_folder, fn) + torch.save(checkpoint, fn) + return fn + + def _categories(fn, detector_options=None): + return get_detector_category_info(fn, detector_options=detector_options) + + ## YOLO-style .pt files + + # Names stored as a list (e.g. MDv5) + fn = _write_model_file('names_list.pt', + {'model': types.SimpleNamespace(names=['animal', 'person', 'vehicle'], nc=3)}) + info = _categories(fn) + assert info['detection_categories'] == DEFAULT_DETECTOR_LABEL_MAP, 'List names mismatch' + assert info['category_id_offset'] == 1, 'List names offset mismatch' + + # Names stored as a dict (e.g. ultralytics) + fn = _write_model_file('names_dict.pt', + {'model': types.SimpleNamespace(names={0: 'cat', 1: 'dog'}, nc=2)}) + info = _categories(fn) + assert info['detection_categories'] == {'0': 'cat', '1': 'dog'}, 'Dict names mismatch' + assert info['category_id_offset'] == 0, 'Dict names offset mismatch' + + # Un-stripped ultralytics checkpoint: model is None, names are on the EMA model + fn = _write_model_file('ema_only.pt', + {'model': None, 'ema': types.SimpleNamespace(names={0: 'cat'}, nc=1)}) + assert _categories(fn)['detection_categories'] == {'0': 'cat'}, 'EMA names mismatch' + + # Names only available in the model yaml + fn = _write_model_file('yaml_names.pt', + {'model': types.SimpleNamespace(yaml={'nc': 2, 'names': ['cat', 'dog']})}) + assert _categories(fn)['detection_categories'] == {'0': 'cat', '1': 'dog'}, \ + 'YAML names mismatch' + + # No names, but a class count + fn = _write_model_file('no_names.pt', {'model': types.SimpleNamespace(nc=2)}) + info = _categories(fn) + assert info['detection_categories'] == {'0': 'category_00', '1': 'category_01'}, \ + 'Generated names mismatch' + assert info['category_id_offset'] == 0, 'Generated names offset mismatch' + + # No names and no class count + fn = _write_model_file('no_classes.pt', {'model': types.SimpleNamespace()}) + try: + _categories(fn) + raise AssertionError('Expected an error for a model with no class information') + except ValueError: + pass + + ## RF-DETR-style .pth files + + # class_names in an args dict + fn = _write_model_file('rfdetr_dict.pth', + {'args': {'class_names': ['animal', 'person', 'vehicle']}, + 'model': {'class_embed.bias': torch.zeros(4)}}) + info = _categories(fn) + assert info['detection_categories'] == DEFAULT_DETECTOR_LABEL_MAP, \ + 'RF-DETR MD names mismatch' + assert info['category_id_offset'] == 1, 'RF-DETR MD names offset mismatch' + + # class_names in an args Namespace + fn = _write_model_file('rfdetr_namespace.pth', + {'args': argparse.Namespace(class_names=['fish']), + 'model': {'class_embed.bias': torch.zeros(2)}}) + info = _categories(fn) + assert info['detection_categories'] == {'0': 'fish'}, 'RF-DETR Namespace names mismatch' + assert info['category_id_offset'] == 0, 'RF-DETR Namespace names offset mismatch' + + # No class names: use the size of the classification head + fn = _write_model_file('rfdetr_no_names.pth', + {'args': {'num_queries': 300}, + 'model': {'transformer.enc_out_class_embed.0.bias': torch.zeros(3), + 'class_embed.bias': torch.zeros(3)}}) + assert _categories(fn)['detection_categories'] == \ + {'0': 'category_00', '1': 'category_01', '2': 'category_02'}, \ + 'RF-DETR generated names mismatch' + + ## Class mapping files override the model file + + class_mapping_file = os.path.join(test_folder, 'class_mapping.json') + with open(class_mapping_file, 'w') as f: + json.dump({'0': 'a', '1': 'b'}, f) + fn = os.path.join(test_folder, 'names_list.pt') + info = _categories(fn, detector_options={'class_mapping_filename': class_mapping_file}) + assert info['detection_categories'] == {'0': 'a', '1': 'b'}, '.json class mapping mismatch' + assert info['category_id_offset'] == 0, 'Class mappings should not be offset' + + class_mapping_file = os.path.join(test_folder, 'class_mapping.txt') + with open(class_mapping_file, 'w') as f: + for class_name in ('a', 'b', 'c'): + f.write(class_name + '\n') + info = _categories(fn, + detector_options=['class_mapping_filename={}'.format(class_mapping_file)]) + assert info['detection_categories'] == {'0': 'a', '1': 'b', '2': 'c'}, \ + '.txt class mapping mismatch' + + ## TensorFlow models use the default categories + + fn = os.path.join(test_folder, 'model.pb') + with open(fn, 'wb') as f: + f.write(b'') + info = _categories(fn) + assert info['detection_categories'] == DEFAULT_DETECTOR_LABEL_MAP, 'TF categories mismatch' + assert info['category_id_offset'] == 0, 'TF categories offset mismatch' + + finally: + + shutil.rmtree(test_folder) + +# ...def test_get_detector_category_info(...) diff --git a/megadetector/detection/run_detector_batch.py b/megadetector/detection/run_detector_batch.py index b92e2c17..660ca5f7 100644 --- a/megadetector/detection/run_detector_batch.py +++ b/megadetector/detection/run_detector_batch.py @@ -67,7 +67,8 @@ load_detector,\ try_download_known_detector,\ get_detector_version_from_filename,\ - get_detector_metadata_from_version_string + get_detector_metadata_from_version_string,\ + get_detector_category_info from megadetector.utils import path_utils from megadetector.utils import ct_utils @@ -76,7 +77,7 @@ from megadetector.utils.ct_utils import sort_list_of_dicts_by_key from megadetector.visualization import visualization_utils as vis_utils from megadetector.data_management import read_exif -from megadetector.data_management.yolo_output_to_md_output import read_classes_from_yolo_dataset_file +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP # Numpy FutureWarnings from tensorflow import warnings.filterwarnings('ignore', category=FutureWarning) @@ -1118,40 +1119,6 @@ def _process_image(im_file, # ...def _process_image(...) -def _load_custom_class_mapping(class_mapping_filename): - """ - Allows the use of non-MD models, disables the code that enforces MD-like class lists. - - Args: - class_mapping_filename (str): .json file that maps int-strings to strings, or a YOLOv5 - dataset.yaml file. - - Returns: - dict: maps class IDs (int-strings) to class names - """ - - if class_mapping_filename is None: - return - - run_detector.USE_MODEL_NATIVE_CLASSES = True - if class_mapping_filename.endswith('.json'): - with open(class_mapping_filename,'r') as f: - class_mapping = json.load(f) - elif (class_mapping_filename.endswith('.yml') or class_mapping_filename.endswith('.yaml')): - class_mapping = read_classes_from_yolo_dataset_file(class_mapping_filename) - # convert from ints to int-strings - class_mapping = {str(k):v for k,v in class_mapping.items()} - else: - raise ValueError('Unrecognized class mapping file {}'.format(class_mapping_filename)) - - print('Loaded custom class mapping:') - print(class_mapping) - - # This determines what gets written by write_results_to_file - run_detector.DEFAULT_DETECTOR_LABEL_MAP = class_mapping - return class_mapping - - #%% Main function def load_and_run_detector_batch(model_file, @@ -1197,8 +1164,11 @@ def load_and_run_detector_batch(model_file, image_size (int, optional): image size to use for inference, only mess with this if (a) you're using a model other than MegaDetector or (b) you know what you're doing - class_mapping_filename (str, optional): use a non-default class mapping supplied in a .json - file or YOLOv5 dataset.yaml file + class_mapping_filename (str, optional): use a class mapping supplied in a .json, .txt, or + YOLO dataset.yaml file, rather than the class names stored in the model file; class IDs + in this file should match the class IDs produced by the model (typically starting at + zero). If you use this option, pass the same categories to write_results_to_file() + (see run_detector.get_detector_category_info()). include_image_size (bool, optional): should we include image size in the output for each image? include_image_timestamp (bool, optional): should we include image timestamps in the output for each image? include_exif_tags (str, optional): comma-separated list of EXIF tags to include in output @@ -1244,8 +1214,10 @@ def load_and_run_detector_batch(model_file, if checkpoint_frequency is None or checkpoint_path is None: checkpoint_frequency = -1 + # The class mapping file is passed to the detector via detector_options, so it's available + # wherever the detector is loaded (including worker processes) if class_mapping_filename is not None: - _load_custom_class_mapping(class_mapping_filename) + detector_options['class_mapping_filename'] = class_mapping_filename global verbose if verbose_output: @@ -1770,7 +1742,8 @@ def write_results_to_file(results, info=None, include_max_conf=False, custom_metadata=None, - force_forward_slashes=True): + force_forward_slashes=True, + detection_categories=None): """ Writes list of detection results to JSON output file. Format matches: @@ -1781,8 +1754,9 @@ def write_results_to_file(results, output_file (str): path to JSON output file, should end in '.json' relative_path_base (str, optional): path to a directory as the base for relative paths, can be None if the paths in [results] are absolute - detector_file (str, optional): filename of the detector used to generate these results, only - used to pull out a version number for the "info" field + detector_file (str, optional): filename of the detector used to generate these results, used + to pull out a version number for the "info" field, and to determine the detection categories + if [detection_categories] is None info (dict, optional): dictionary to put in the results file instead of the default "info" field include_max_conf (bool, optional): old files (version 1.2 and earlier) included a "max_conf" field in each image; this was removed in version 1.3. Set this flag to force the inclusion @@ -1791,6 +1765,11 @@ def write_results_to_file(results, a dictionary, but no type/format checks are performed force_forward_slashes (bool, optional): convert all slashes in filenames within [results] to forward slashes + detection_categories (dict, optional): dict mapping string category IDs to category names; if + this is None, categories are read from [detector_file] (see + run_detector.get_detector_category_info()), or, if [detector_file] is also None, the + default MD categories are used. Raises an error if any detection in [results] uses a + category that is not in the detection categories. Returns: dict: the MD-formatted dictionary that was written to [output_file] @@ -1863,9 +1842,30 @@ def write_results_to_file(results, else: im['detections'] = None + ## Determine the detection categories + + if detection_categories is None: + if detector_file is not None: + detection_categories = \ + get_detector_category_info(detector_file)['detection_categories'] + else: + print('Warning (write_results_to_file): no detection categories or detector file ' + \ + 'supplied, using default MegaDetector categories') + detection_categories = dict(DEFAULT_DETECTOR_LABEL_MAP) + + # Make sure every detection uses one of these categories + for im in results: + if ('detections' not in im) or (im['detections'] is None): + continue + for det in im['detections']: + if det['category'] not in detection_categories: + raise ValueError( + 'Detection category {} (in {}) is not in the detection categories ({})'.format( + det['category'], im['file'], ','.join(detection_categories.keys()))) + final_output = { 'images': results, - 'detection_categories': run_detector.DEFAULT_DETECTOR_LABEL_MAP, + 'detection_categories': detection_categories, 'info': info } @@ -2079,9 +2079,10 @@ def main(): # noqa '--class_mapping_filename', type=str, default=None, - help='Use a non-default class mapping, supplied in a .json file with a dictionary mapping' + \ - 'int-strings to strings. This will also disable the addition of "1" to all category ' + \ - 'IDs, so your class mapping should start at zero. Can also be a YOLOv5 dataset.yaml file.') + help='Use a class mapping supplied in a .json file with a dictionary mapping int-strings ' + \ + 'to strings, rather than the class names stored in the model file. Class IDs in this file ' + \ + 'should match the class IDs produced by the model (typically starting at zero). Can also ' + \ + 'be a YOLO dataset.yaml file or a .txt file with one class name per line.') parser.add_argument( '--include_image_size', action='store_true', @@ -2192,8 +2193,13 @@ def main(): # noqa assert not os.path.isdir(args.output_file), 'Specified output file is a directory' + # Determine the detection categories now (rather than after inference), so we fail early if + # we can't determine categories for this model. + category_detector_options = dict(detector_options) if args.class_mapping_filename is not None: - _load_custom_class_mapping(args.class_mapping_filename) + category_detector_options['class_mapping_filename'] = args.class_mapping_filename + detection_categories = get_detector_category_info( + args.detector_file, detector_options=category_detector_options)['detection_categories'] # Load the checkpoint if available # @@ -2271,7 +2277,7 @@ def main(): # noqa with open(args.previous_results_file,'r') as f: previous_results = json.load(f) - assert previous_results['detection_categories'] == run_detector.DEFAULT_DETECTOR_LABEL_MAP, \ + assert previous_results['detection_categories'] == detection_categories, \ "Can't merge previous results when those results use a different set of detection categories" print('Loaded previous results for {} images from {}'.format( @@ -2383,7 +2389,8 @@ def main(): # noqa args.output_file, relative_path_base=relative_path_base, detector_file=args.detector_file, - include_max_conf=args.include_max_conf) + include_max_conf=args.include_max_conf, + detection_categories=detection_categories) if checkpoint_path and os.path.isfile(checkpoint_path): os.remove(checkpoint_path) diff --git a/megadetector/detection/run_inference_with_yolov5_val.py b/megadetector/detection/run_inference_with_yolov5_val.py index a8190b79..3bb13bfb 100644 --- a/megadetector/detection/run_inference_with_yolov5_val.py +++ b/megadetector/detection/run_inference_with_yolov5_val.py @@ -60,6 +60,7 @@ from megadetector.utils.path_utils import path_is_abs from megadetector.data_management import yolo_output_to_md_output from megadetector.detection.run_detector import try_download_known_detector +from megadetector.detection.run_detector import MEGADETECTOR_MODEL_CLASS_NAMES from megadetector.postprocessing.combine_batch_outputs import combine_batch_output_files default_image_size_with_augmentation = int(1280 * 1.3) @@ -157,12 +158,13 @@ def __init__(self): self.remove_yolo_results_folder = True #: These are deliberately offset from the standard MD categories; YOLOv5 - #: needs categories IDs to start at 0. + #: needs categories IDs to start at 0. The default is the default MD categories, + #: offset by -1. #: #: This can also be a string that points to any class mapping file supported #: by read_classes_from_yolo_dataset_file(): a YOLO dataset.yaml file, a text #: file with a list of classes, or a .json file with an ID --> name dict - self.yolo_category_id_to_name = {0:'animal',1:'person',2:'vehicle'} + self.yolo_category_id_to_name = dict(MEGADETECTOR_MODEL_CLASS_NAMES) #: What should we do if the output file already exists? #: diff --git a/megadetector/detection/tf_detector.py b/megadetector/detection/tf_detector.py index f29715a2..36ca635a 100644 --- a/megadetector/detection/tf_detector.py +++ b/megadetector/detection/tf_detector.py @@ -11,7 +11,7 @@ import numpy as np from megadetector.detection.run_detector import \ - CONF_DIGITS, COORD_DIGITS, FAILURE_INFER + CONF_DIGITS, COORD_DIGITS, FAILURE_INFER, get_detector_category_info from megadetector.utils.ct_utils import truncate_float import tensorflow.compat.v1 as tf @@ -44,9 +44,16 @@ def __init__(self, model_path, detector_options=None): Args: model_path (str): path to .pb file detector_options (dict, optional): key-value pairs that control detector - options; currently not used by TFDetector + options; only used to supply a custom class mapping file (see + run_detector.get_detector_category_info()) """ + #: Maps string category IDs to category names, in the format used for the + #: 'detection_categories' field in MD output files. TF MegaDetector models produce + #: 1-indexed class IDs that correspond directly to the default MD categories. + category_info = get_detector_category_info(model_path, detector_options=detector_options) + self.detection_categories = category_info['detection_categories'] + detection_graph = TFDetector.__load_model(model_path) self.tf_session = tf.Session(graph=detection_graph) self.image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') @@ -183,8 +190,14 @@ def generate_detections_one_image(self, max_detection_conf = 0.0 for b, s, c in zip(boxes, scores, classes): #noqa if s > detection_threshold: + # Use string type for the numerical class label, not int + category_id = str(int(c)) + if category_id not in self.detection_categories: + raise KeyError('Model predicted category {}, which is not one of '.format( + category_id) + 'the categories for this detector ({})'.format( + ','.join(self.detection_categories.keys()))) detection_entry = { - 'category': str(int(c)), # use string type for the numerical class label, not int + 'category': category_id, 'conf': truncate_float(float(s), # cast to float for json serialization precision=CONF_DIGITS), 'bbox': TFDetector.__convert_coords(b) diff --git a/megadetector/postprocessing/convert_output_format.py b/megadetector/postprocessing/convert_output_format.py index e4574037..5b9a83db 100644 --- a/megadetector/postprocessing/convert_output_format.py +++ b/megadetector/postprocessing/convert_output_format.py @@ -254,7 +254,7 @@ def convert_csv_to_json(input_path,output_path=None,overwrite=True): } classification_categories = {} - detection_categories = annotation_constants.detector_bbox_categories + detection_categories = dict(annotation_constants.DEFAULT_DETECTOR_LABEL_MAP) images = [] diff --git a/megadetector/postprocessing/md_to_labelme.py b/megadetector/postprocessing/md_to_labelme.py index afddda90..3bc2d320 100644 --- a/megadetector/postprocessing/md_to_labelme.py +++ b/megadetector/postprocessing/md_to_labelme.py @@ -29,7 +29,8 @@ from megadetector.visualization.visualization_utils import open_image from megadetector.utils.ct_utils import round_float from megadetector.utils.ct_utils import write_json -from megadetector.detection.run_detector import DEFAULT_DETECTOR_LABEL_MAP, FAILURE_IMAGE_OPEN +from megadetector.detection.run_detector import FAILURE_IMAGE_OPEN +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP output_precision = 3 default_confidence_threshold = 0.15 diff --git a/megadetector/utils/wi_platform_utils.py b/megadetector/utils/wi_platform_utils.py index 170e751c..5d935da0 100644 --- a/megadetector/utils/wi_platform_utils.py +++ b/megadetector/utils/wi_platform_utils.py @@ -39,7 +39,7 @@ from megadetector.utils.wi_taxonomy_utils import no_cv_result_prediction_string from megadetector.utils.wi_taxonomy_utils import blank_prediction_string -from megadetector.detection.run_detector import DEFAULT_DETECTOR_LABEL_MAP +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP # Only used when pushing results directly to the platform via the API; any detections we want # to show in the UI should have at least this confidence value. diff --git a/megadetector/utils/wi_taxonomy_utils.py b/megadetector/utils/wi_taxonomy_utils.py index 2ce1b31f..0c69a83f 100644 --- a/megadetector/utils/wi_taxonomy_utils.py +++ b/megadetector/utils/wi_taxonomy_utils.py @@ -32,7 +32,7 @@ from megadetector.postprocessing.validate_batch_results import \ validate_batch_results, ValidateBatchResultsOptions -from megadetector.detection.run_detector import DEFAULT_DETECTOR_LABEL_MAP +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP from megadetector.detection.run_detector_batch import current_format_version md_category_id_to_name = DEFAULT_DETECTOR_LABEL_MAP diff --git a/megadetector/visualization/visualization_utils.py b/megadetector/visualization/visualization_utils.py index e3ec8584..e1067b77 100644 --- a/megadetector/visualization/visualization_utils.py +++ b/megadetector/visualization/visualization_utils.py @@ -26,8 +26,6 @@ from megadetector.utils.path_utils import find_images from megadetector.data_management import annotation_constants -from megadetector.data_management.annotation_constants import \ - detector_bbox_category_id_to_name from megadetector.utils.ct_utils import sort_list_of_dicts_by_key from megadetector.utils.ct_utils import round_float @@ -50,11 +48,6 @@ VTEXTALIGN_TOP = 0 VTEXTALIGN_BOTTOM = 1 -# Convert category ID from int to str -DEFAULT_DETECTOR_LABEL_MAP = { - str(k): v for k, v in detector_bbox_category_id_to_name.items() -} - # Constants controlling retry behavior when fetching images from URLs n_retries = 10 retry_sleep_time = 0.01 @@ -1178,13 +1171,17 @@ def render_megadb_bounding_boxes(boxes_info, image): display_strs = [] classes = [] # ints, for selecting colors + detector_category_name_to_id = {} + for category_id, category_name in annotation_constants.DEFAULT_DETECTOR_LABEL_MAP.items(): + detector_category_name_to_id[category_name] = int(category_id) + for b in boxes_info: x_min, y_min, w_rel, h_rel = b['bbox'] y_max = y_min + h_rel x_max = x_min + w_rel display_boxes.append([y_min, x_min, y_max, x_max]) display_strs.append([b['category']]) - classes.append(annotation_constants.detector_bbox_category_name_to_id[b['category']]) + classes.append(detector_category_name_to_id[b['category']]) display_boxes = np.array(display_boxes) draw_bounding_boxes_on_image(image, display_boxes, classes, display_strs=display_strs) @@ -1314,7 +1311,7 @@ def draw_bounding_boxes_on_file(input_file, output_file, detections, confidence_threshold=0.0, - detector_label_map=DEFAULT_DETECTOR_LABEL_MAP, + detector_label_map=annotation_constants.DEFAULT_DETECTOR_LABEL_MAP, thickness=DEFAULT_BOX_THICKNESS, expansion=0, colormap=None, diff --git a/megadetector/visualization/visualize_detector_output.py b/megadetector/visualization/visualize_detector_output.py index abc3270c..590ac21b 100644 --- a/megadetector/visualization/visualize_detector_output.py +++ b/megadetector/visualization/visualize_detector_output.py @@ -19,7 +19,7 @@ from functools import partial from tqdm import tqdm -from megadetector.data_management.annotation_constants import detector_bbox_category_id_to_name +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP from megadetector.detection.run_detector import get_typical_confidence_threshold_from_results from megadetector.utils.ct_utils import get_max_conf from megadetector.utils.ct_utils import sort_list_of_dicts_by_key @@ -34,14 +34,6 @@ default_box_sort_order = 'confidence' -#%% Constants - -# This will only be used if a category mapping is not available in the results file. -DEFAULT_DETECTOR_LABEL_MAP = { - str(k): v for k, v in detector_bbox_category_id_to_name.items() -} - - #%% Support functions def _render_image(entry, @@ -289,6 +281,7 @@ def visualize_detector_output(detector_output_path, elif 'detection_categories' in detector_output: detector_label_map = detector_output['detection_categories'] else: + # Only used if a category mapping is not available in the results file detector_label_map = DEFAULT_DETECTOR_LABEL_MAP num_images = len(images) diff --git a/megadetector/visualization/visualize_video_output.py b/megadetector/visualization/visualize_video_output.py index c8d78ed0..e10b1d03 100644 --- a/megadetector/visualization/visualize_video_output.py +++ b/megadetector/visualization/visualize_video_output.py @@ -21,7 +21,7 @@ from PIL import Image import numpy as np -from megadetector.data_management.annotation_constants import detector_bbox_category_id_to_name +from megadetector.data_management.annotation_constants import DEFAULT_DETECTOR_LABEL_MAP from megadetector.detection.video_utils import run_callback_on_frames, default_fourcc, is_video_file from megadetector.utils.path_utils import path_is_abs from megadetector.utils.path_utils import clean_filename @@ -32,11 +32,6 @@ #%% Constants -# This will only be used if a category mapping is not available in the results file -DEFAULT_DETECTOR_LABEL_MAP = { - str(k): v for k, v in detector_bbox_category_id_to_name.items() -} - DEFAULT_CLASSIFICATION_THRESHOLD = 0.4 DEFAULT_DETECTION_THRESHOLD = 0.15 @@ -648,7 +643,8 @@ def visualize_video_output(detector_output_path, print('Loading results from {}'.format(detector_output_path)) results_data = load_md_or_speciesnet_file(detector_output_path) - # Get label mappings + # Get label mappings; the default detector categories are only used if a category + # mapping is not available in the results file detector_label_map = results_data.get('detection_categories', DEFAULT_DETECTOR_LABEL_MAP) classification_label_map = results_data.get('classification_categories', {})