Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions megadetector/data_management/animl_to_md.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 20 additions & 22 deletions megadetector/data_management/annotation_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
4 changes: 2 additions & 2 deletions megadetector/data_management/zamba_to_md.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 = {}

Expand Down
38 changes: 23 additions & 15 deletions megadetector/detection/pytorch_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
})
Expand Down
72 changes: 52 additions & 20 deletions megadetector/detection/rfdetr_detector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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, \
Expand Down Expand Up @@ -247,39 +247,35 @@ 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(...)


#%% 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.

Args:
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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading