### Install SAHI from Source Source: https://obss.github.io/sahi/quick-start Install SAHI directly from its GitHub repository. This is useful for getting the latest development version. ```bash pip install git+https://github.com/obss/sahi.git@main ``` -------------------------------- ### Install Ultralytics Framework Source: https://obss.github.io/sahi/quick-start Install the Ultralytics framework, a common choice for object detection models used with SAHI. ```bash pip install ultralytics ``` -------------------------------- ### Install Project Dependencies Source: https://obss.github.io/sahi/contributing Install core and development dependencies using `uv sync`. For specific model testing, additional dependencies may be required. ```bash # Install core + dev dependencies uv sync --extra dev # For testing specific models, install their dependencies. ``` -------------------------------- ### Clone SAHI Repository and Install Dependencies Source: https://obss.github.io/sahi/notebooks Clone the SAHI repository from GitHub and install the necessary development dependencies to run the notebooks locally. This setup is required before launching Jupyter. ```bash git clone https://github.com/obss/sahi.git cd sahi pip install -e "[dev]" jupyter notebook demo/ ``` -------------------------------- ### Install SAHI Source: https://obss.github.io/sahi/quick-start Install SAHI using pip. This is the primary method for adding SAHI to your project. ```bash pip install sahi ``` -------------------------------- ### Install YOLOv5 Package Source: https://obss.github.io/sahi/guides/models Install the yolov5 package to use classic YOLOv5 models. ```bash pip install yolov5 ``` -------------------------------- ### Install MMDetection Packages Source: https://obss.github.io/sahi/guides/models Install mmdet, mmcv, and mmengine to use the full MMDetection model zoo. ```bash pip install mmdet mmcv mmengine ``` -------------------------------- ### Install HuggingFace Transformers and TIMM Source: https://obss.github.io/sahi/guides/models Install the transformers and timm packages to use object detection models from the HuggingFace Hub. ```bash pip install transformers timm ``` -------------------------------- ### Get Package Information Source: https://obss.github.io/sahi/api Retrieves whether a package is installed and its version string. Logs the version if verbose is True. Returns 'N/A' for the version if the package is not installed. ```python import importlib.metadata as _importlib_metadata import importlib import logging from packaging import version logger = logging.getLogger(__name__) def get_package_info(package_name: str, verbose: bool = True) -> tuple[bool, str]: """Check whether a package is installed and retrieve its version. Args: package_name: The name of the package to look up. verbose: If True, log the package version when available. Returns: is_available (bool): Whether the package is installed. version_string (str): Version string, or "N/A" if not installed. """ _is_available = is_available(package_name) if _is_available: try: _version = _importlib_metadata.version(package_name) except (ModuleNotFoundError, AttributeError): try: _version = importlib.import_module(package_name).__version__ except AttributeError: _version = "unknown" if verbose: logger.pkg_info(f"{package_name} version {_version} is available.") else: _version = "N/A" return _is_available, _version ``` -------------------------------- ### Install RF-DETR Source: https://obss.github.io/sahi/guides/models Install the RF-DETR library using pip. This is a prerequisite for using RF-DETR models. ```bash pip install rfdetr ``` -------------------------------- ### Install PyTorch and TorchVision Source: https://obss.github.io/sahi/guides/models Install torch and torchvision to use built-in TorchVision detection models like Faster R-CNN and RetinaNet. ```bash pip install torch torchvision ``` -------------------------------- ### Install Detectron2 Package Source: https://obss.github.io/sahi/guides/models Install the detectron2 package to use Facebook's Detectron2 models for detection and instance segmentation. ```bash pip install detectron2 ``` -------------------------------- ### Development Installation of SAHI Source: https://obss.github.io/sahi/quick-start Install SAHI in editable mode for development. This allows you to make changes to the SAHI code and see them reflected immediately without reinstalling. ```bash git clone https://github.com/obss/sahi cd sahi pip install -e . ``` -------------------------------- ### Install SAHI with Conda Source: https://obss.github.io/sahi/quick-start Install SAHI using Conda, suitable for environments where Conda is the preferred package manager. ```bash conda install -c conda-forge sahi ``` -------------------------------- ### Install Ultralytics for YOLO Models Source: https://obss.github.io/sahi/guides/models Install the ultralytics package to use YOLOv8, YOLO11, YOLO26, and other Ultralytics model variants. ```bash pip install ultralytics ``` -------------------------------- ### Display SAHI Environment Information Source: https://obss.github.io/sahi/cli Display installed package versions related to SAHI. This command provides a quick way to check your SAHI installation and its dependencies. ```bash sahi env ``` -------------------------------- ### Get MMDetection Version as Integer Source: https://obss.github.io/sahi/api Retrieves the installed MMDetection version and converts it into an integer format for easier comparison or processing. ```python def mmdet_version_as_integer() -> int: """Get the MMDetection version as an integer.""" import mmdet return int(mmdet.__version__.replace(".", "")) ``` -------------------------------- ### __init__ Source: https://obss.github.io/sahi/api Initializes the postprocessor with configurable matching parameters such as threshold, metric, and classagnostic behavior. ```APIDOC ## __init__ (match_threshold=0.5, match_metric='IOU', class_agnostic=True) ### Description Initialize the postprocessor with matching configuration. ### Parameters #### Path Parameters - **match_threshold** (float) - Optional - Minimum overlap value to consider predictions matching. Default: 0.5 - **match_metric** (str) - Optional - Metric for overlap computation, "IOU" or "IOS". Default: 'IOU' - **class_agnostic** (bool) - Optional - If True, apply postprocessing across all categories. Default: True ``` -------------------------------- ### __init__ Source: https://obss.github.io/sahi/api Initializes the Detectron2 detection model, setting up required packages. ```APIDOC ## __init__ ### Description Initializes the Detectron2 detection model, setting up required packages including torch and detectron2. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `*args` (object) - Variable length argument list passed to DetectionModel. - `**kwargs` (object) - Arbitrary keyword arguments passed to DetectionModel. ``` -------------------------------- ### Check Package Availability and Version Source: https://obss.github.io/sahi/api Use this function to determine if a Python package is installed and to get its version. It handles cases where the version might be unknown or outdated, raising an ImportError if a minimum version is not met. ```python from sahi.utils.import_utils import get_package_info _is_available, _version = get_package_info(package_name, verbose=verbose) if _is_available: if _version == "unknown": logger.warning( f"Could not determine version of {package_name}. Assuming version {minimum_version} is compatible." ) else: if version.parse(_version) < version.parse(minimum_version): raise ImportError( f"Please upgrade {package_name} to version {minimum_version} or higher to use this module." ) yield ``` -------------------------------- ### Install PyTorch and Ultralytics for CUDA Source: https://obss.github.io/sahi/quick-start Install PyTorch, torchvision, pytorch-cuda, and ultralytics in a single Conda command for CUDA environments. Ensure compatibility by installing them together. ```bash conda install -c pytorch -c nvidia -c conda-forge pytorch torchvision pytorch-cuda=11.8 ultralytics ``` -------------------------------- ### __init__(*args, **kwargs) Source: https://obss.github.io/sahi/models/detectron2 Initializes the Detectron2 detection model. It sets up the required packages and calls the parent class constructor. ```APIDOC ## __init__(*args, **kwargs) ### Description Initialize Detectron2 detection model. ### Parameters #### Path Parameters - `*args` (object) - Required - Variable length argument list passed to DetectionModel. - `**kwargs` (object) - Required - Arbitrary keyword arguments passed to DetectionModel. ``` -------------------------------- ### __init__ Source: https://obss.github.io/sahi/models/yolov5 Initializes the YOLOv5 detection model. It sets up the required packages and calls the superclass constructor. ```APIDOC ## __init__ ### Description Initializes YOLOv5 detection model. ### Method Signature `__init__(*args, **kwargs)` ### Parameters * `*args`: Variable length argument list. * `**kwargs`: Arbitrary keyword arguments. ### Source Code ```python def __init__(self, *args: object, **kwargs: object) -> None: """Initialize YOLOv5 detection model.""" existing_packages = getattr(self, "required_packages", None) or [] self.required_packages = [*list(existing_packages), "yolov5", "torch"] super().__init__(*args, **kwargs) # type: ignore[misc, arg-type] ``` ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://obss.github.io/sahi/contributing Set up a Python 3.10 virtual environment using `uv` and activate it. This ensures project dependencies are isolated. ```bash pip install uv uv venv --python 3.10 source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### __init__ Source: https://obss.github.io/sahi/models/base Initializes the object detection/instance segmentation model with various configuration options. ```APIDOC ## `__init__` ### Description Init object detection/instance segmentation model. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **model_path** (str | None) - Optional - Path for the instance segmentation model weight - **model** (Any | None) - Optional - A pre-loaded detection model instance. - **config_path** (str | None) - Optional - Path for the mmdetection instance segmentation model config file - **device** (str | None) - Optional - Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. - **mask_threshold** (float) - Optional - Value to threshold mask pixels, should be between 0 and 1. Default: 0.5 - **confidence_threshold** (float) - Optional - All predictions with score < confidence_threshold will be discarded. Default: 0.3 - **category_mapping** (dict | None) - Optional - Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} - **category_remapping** (dict | None) - Optional - Remap category ids based on category names, after performing inference e.g. {"car": 3} - **load_at_init** (bool) - Optional - If True, automatically loads the model at initialization. Default: True - **image_size** (int | None) - Optional - Inference input size. ### Request Example ```python from sahi.models.base import BaseSahiModel model = BaseSahiModel(model_path="path/to/your/model.pt", config_path="path/to/your/config.py") ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Initialize Legacy Postprocessor Source: https://obss.github.io/sahi/api Initializes the postprocessor with configuration for matching predictions. Supports 'IOU' or 'IOS' as matching metrics and allows for class-agnostic matching. ```python def __init__( self, match_threshold: float = 0.5, match_metric: str = "IOU", class_agnostic: bool = True, ) -> None: """Initialize the postprocessor with matching configuration. Args: match_threshold: Minimum overlap value to consider predictions matching. match_metric: Metric for overlap computation, "IOU" or "IOS". class_agnostic: If True, apply postprocessing across all categories. """ self.match_threshold = match_threshold self.class_agnostic = class_agnostic if match_metric == "IOU": self.calculate_match = self.calculate_bbox_iou elif match_metric == "IOS": self.calculate_match = self.calculate_bbox_ios else: raise ValueError(f"'match_metric' should be one of ['IOU', 'IOS'] but given as {match_metric}") ``` -------------------------------- ### check_package_minimum_version Source: https://obss.github.io/sahi/api Checks if an installed Python package meets a specified minimum version requirement. It returns True if the package is missing, its version is unknown, or if the installed version meets or exceeds the minimum. It returns False if the installed version is below the minimum. ```APIDOC ## check_package_minimum_version(package_name, minimum_version, verbose=False) ### Description Check whether an installed package meets a minimum version requirement. ### Parameters #### Path Parameters - **package_name** (str) - Required - The name of the package to check. - **minimum_version** (str) - Required - The minimum acceptable version string (e.g. "1.0.0"). - **verbose** (bool) - Optional - If True, log the detected package version. Defaults to False. ### Returns - **bool** - True if the package is missing, its version is unknown, or its version meets the minimum. False if the installed version is below the minimum. ``` -------------------------------- ### Initialize Postprocessor Source: https://obss.github.io/sahi/postprocess/backends Initializes the postprocessor with configuration parameters for matching. ```python def __init__( self, match_threshold: float = 0.5, match_metric: str = "IOU", class_agnostic: bool = True, ) -> None: """Initialize the postprocessor with configuration parameters. Args: match_threshold: Minimum overlap value (IoU or IoS) to consider two predictions as matching. match_metric: Overlap metric, "IOU" or "IOS". class_agnostic: If True, apply postprocessing across all categories. If False, apply per category independently. """ self.match_threshold = match_threshold self.class_agnostic = class_agnostic self.match_metric = match_metric ``` -------------------------------- ### __init__ Source: https://obss.github.io/sahi/api Initialize MMDetection detection model. ```APIDOC ## __init__ ### Description Initialize MMDetection detection model. ### Parameters - **model_path** (str | None) - Optional - Path to the model file. - **model** (object | None) - Optional - Pre-loaded model object. - **config_path** (str | None) - Optional - Path to the model configuration file. - **device** (str | None) - Optional - Device to run the model on (e.g., 'cuda', 'cpu'). - **mask_threshold** (float) - Optional - Threshold for mask prediction. Defaults to 0.5. - **confidence_threshold** (float) - Optional - Threshold for confidence score. Defaults to 0.3. - **category_mapping** (dict | None) - Optional - Mapping for category IDs. - **category_remapping** (dict | None) - Optional - Remapping for category names. - **load_at_init** (bool) - Optional - Whether to load the model at initialization. Defaults to True. - **image_size** (int | None) - Optional - Expected image size. - **scope** (str) - Optional - Scope for the model. Defaults to 'mmdet'. ``` -------------------------------- ### Install Dev Dependencies for CI Fix Source: https://obss.github.io/sahi/contributing Install development dependencies to fix CI build failures related to formatting. ```bash uv sync --extra dev ``` -------------------------------- ### Download YOLOv5-Nano Model Source: https://obss.github.io/sahi/api Downloads the YOLOv5-Nano model to a specified or default path. Creates parent directories if they do not exist. ```python def download_yolov5n_model(destination_path: str | None = None) -> None: """Download the YOLOv5-Nano model for testing.""" if destination_path is None: destination_path = Yolov5TestConstants.YOLOV5N_MODEL_PATH Path(destination_path).parent.mkdir(parents=True, exist_ok=True) if not path.exists(destination_path): urllib.request.urlretrieve( Yolov5TestConstants.YOLOV5N_MODEL_URL, destination_path, ) ``` -------------------------------- ### Initialize Yolov5DetectionModel Source: https://obss.github.io/sahi/models/yolov5 Initializes the Yolov5DetectionModel, adding 'yolov5' and 'torch' to required packages. ```python class Yolov5DetectionModel(DetectionModel): """YOLOv5 object detection model. Wraps Ultralytics YOLOv5 for fast object detection. """ def __init__(self, *args: object, **kwargs: object) -> None: """Initialize YOLOv5 detection model.""" existing_packages = getattr(self, "required_packages", None) or [] self.required_packages = [*list(existing_packages), "yolov5", "torch"] super().__init__(*args, **kwargs) # type: ignore[misc, arg-type] ``` -------------------------------- ### Get and Set Category Name Source: https://obss.github.io/sahi/utils/coco Use the `category_name` property to get or set the name of the annotation's category. The setter ensures that the provided category name is a string. ```python @property def category_name(self) -> str | None: """Returns category name of the annotation as str.""" return self._category_name @category_name.setter def category_name(self, n: str) -> None: if not isinstance(n, str): raise Exception("category_name must be a string") self._category_name = n ``` -------------------------------- ### sahi.cli.app Source: https://obss.github.io/sahi/api Command-line interface application entry point for SAHI. ```APIDOC ## `app()` ### Description Entry point for the SAHI command-line interface application. ### Function Signature ```python def app() -> None: """Cli app.""" fire.Fire(sahi_app) ``` ``` -------------------------------- ### Get and Set Category ID Source: https://obss.github.io/sahi/utils/coco The `category_id` property allows you to get and set the category identifier for the annotation. The setter includes a type check to ensure that the `category_id` is always an integer. ```python @property def category_id(self) -> int: """Returns category id of the annotation as int.""" return self._category_id @category_id.setter def category_id(self, i: int) -> None: if not isinstance(i, int): raise Exception("category_id must be an integer") self._category_id = i ``` -------------------------------- ### Check Package Minimum Version Source: https://obss.github.io/sahi/api Verifies if an installed package meets a specified minimum version. Logs the detected version if verbose is True. Returns False only if the installed version is below the minimum. ```python def check_package_minimum_version(package_name: str, minimum_version: str, verbose: bool = False) -> bool: """Check whether an installed package meets a minimum version requirement. Args: package_name: The name of the package to check. minimum_version: The minimum acceptable version string (e.g. "1.0.0"). verbose: If True, log the detected package version. Returns: True if the package is missing (assumed compatible), its version is unknown, or its version meets the minimum. False if the installed version is below the minimum. """ from packaging import version _is_available, _version = get_package_info(package_name, verbose=verbose) if _is_available: if _version == "unknown": logger.warning( f"Could not determine version of {package_name}. Assuming version {minimum_version} is compatible." ) else: if version.parse(_version) < version.parse(minimum_version): return False return True ``` -------------------------------- ### Initialize SAHI CLI App Source: https://obss.github.io/sahi/api Initializes the command-line interface application for SAHI using the fire library. This function serves as the entry point for SAHI's CLI. ```python def app() -> None: """Cli app.""" fire.Fire(sahi_app) ``` -------------------------------- ### Detectron2 Model Initialization Source: https://obss.github.io/sahi/api Initializes the Detectron2 detection model. This is the entry point for using Detectron2 models with Sahi. ```APIDOC ## `__init__(*args, **kwargs)` ### Description Initialize Detectron2 detection model. ### Parameters * `*args`: Positional arguments. * `**kwargs`: Keyword arguments. ``` -------------------------------- ### get_package_info Source: https://obss.github.io/sahi/api Checks if a specified Python package is installed and retrieves its version. It can optionally log the package version if verbose is set to True. Raises an ImportError if the installed version is less than a specified minimum version. ```APIDOC ## get_package_info(package_name, verbose=True) ### Description Check whether a package is installed and retrieve its version. ### Parameters #### Path Parameters - **package_name** (str) - Required - The name of the package to look up. - **verbose** (bool) - Optional - If True, log the package version when available. Defaults to True. ### Returns - **is_available** (bool) - Whether the package is installed. - **version_string** (str) - Version string, or "N/A" if not installed. ``` -------------------------------- ### Initialize DetectionModel in SAHI Source: https://obss.github.io/sahi/api Initializes the DetectionModel with various configuration options. Use 'load_at_init=True' to automatically load the model upon instantiation. Ensure necessary dependencies are met. ```python class DetectionModel: """Base class for all detection models in SAHI. Subclasses must implement ``load_model``, ``perform_inference``, and ``_create_object_prediction_list_from_original_predictions`` to integrate a new detection framework. The base class handles device management, dependency checking, category remapping, and the public prediction API. """ required_packages: list[str] | None = None def __init__( self, model_path: str | None = None, model: Any | None = None, config_path: str | None = None, device: str | None = None, mask_threshold: float = 0.5, confidence_threshold: float = 0.3, category_mapping: dict | None = None, category_remapping: dict | None = None, load_at_init: bool = True, image_size: int | None = None, ) -> None: """Init object detection/instance segmentation model. Args: model_path: str Path for the instance segmentation model weight model: Any A pre-loaded detection model instance. config_path: str Path for the mmdetection instance segmentation model config file device: Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. mask_threshold: float Value to threshold mask pixels, should be between 0 and 1 confidence_threshold: float All predictions with score < confidence_threshold will be discarded category_mapping: dict: str to str Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} category_remapping: dict: str to int Remap category ids based on category names, after performing inference e.g. {"car": 3} load_at_init: bool If True, automatically loads the model at initialization image_size: int Inference input size. """ self.model_path = model_path self.config_path = config_path self.model: Any = None self.mask_threshold = mask_threshold self.confidence_threshold = confidence_threshold self.category_mapping = category_mapping self.category_remapping = category_remapping self.image_size = image_size self._original_predictions: Any = None self._object_prediction_list_per_image: list[list[ObjectPrediction]] | None = None self._batch_images: list[np.ndarray] | None = None self._original_shapes: list[tuple[int, ...]] | None = None self.set_device(device) # automatically ensure dependencies self.check_dependencies() # automatically load model if load_at_init is True if load_at_init: if model: self.set_model(model) else: self.load_model() def check_dependencies(self, packages: list[str] | None = None) -> None: """Ensures required dependencies are installed. If 'packages' is None, uses self.required_packages. Subclasses may still call with a custom list for dynamic needs. """ ``` -------------------------------- ### mmdet_version_as_integer Source: https://obss.github.io/sahi/api Get the MMDetection version as an integer. ```APIDOC ## mmdet_version_as_integer() ### Description Get the MMDetection version as an integer. ### Returns - **int** - The MMDetection version as an integer (e.g., 20201 for v2.0.2). ``` -------------------------------- ### CocoAnnotation.iscrowd Source: https://obss.github.io/sahi/api Gets the iscrowd flag for the annotation. ```APIDOC ## CocoAnnotation.iscrowd ### Description Returns iscrowd info of the annotation. ### Property `iscrowd` (int) ``` -------------------------------- ### __post_init__() Source: https://obss.github.io/sahi/annotation Validates bounding box coordinates and shift amount upon initialization. ```APIDOC ## __post_init__() ### Description Validates bounding box coordinates and shift amount. ### Method `__post_init__(self) -> None` ### Parameters None ### Returns None ### Raises ValueError: If box does not contain 4 non-negative floats or if shift_amount does not contain 2 integers. ``` -------------------------------- ### Postprocessor Initialization Source: https://obss.github.io/sahi/postprocess/backends Initializes the postprocessor with configuration parameters for matching predictions. ```APIDOC ## __init__(match_threshold=0.5, match_metric='IOU', class_agnostic=True) ### Description Initialize the postprocessor with configuration parameters. ### Parameters #### Path Parameters - **match_threshold** (float) - Optional - Minimum overlap value (IoU or IoS) to consider two predictions as matching. Default: 0.5 - **match_metric** (str) - Optional - Overlap metric, "IOU" or "IOS". Default: 'IOU' - **class_agnostic** (bool) - Optional - If True, apply postprocessing across all categories. If False, apply per category independently. Default: True ``` -------------------------------- ### CocoAnnotation.category_name Source: https://obss.github.io/sahi/api Gets or sets the category name of the annotation. ```APIDOC ## CocoAnnotation.category_name ### Description Gets or sets the category name of the annotation. ### Property `category_name` (str | None) ### Setter `category_name(self, n: str) -> None` ### Setter Parameters #### Arguments - **n** (str) - The new category name. Must be a string. ``` -------------------------------- ### CocoAnnotation.category_id Source: https://obss.github.io/sahi/api Gets or sets the category ID of the annotation. ```APIDOC ## CocoAnnotation.category_id ### Description Gets or sets the category id of the annotation. ### Property `category_id` (int) ### Setter `category_id(self, i: int) -> None` ### Setter Parameters #### Arguments - **i** (int) - The new category ID. Must be an integer. ``` -------------------------------- ### ObjectPredictionList To Tensor Source: https://obss.github.io/sahi/api Convert to torch.Tensor. Requires torch to be installed. ```APIDOC ## totensor ### Description Convert to torch.Tensor. Requires torch to be installed. ### Method totensor ### Endpoint None ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns object: A torch.Tensor representation of the predictions. ``` -------------------------------- ### Yolov5DetectionModel Initialization Source: https://obss.github.io/sahi/models/yolov5 Initializes the YOLOv5 detection model, ensuring necessary packages like 'yolov5' and 'torch' are available. ```APIDOC ## Yolov5DetectionModel.__init__ ### Description Initializes the YOLOv5 detection model. ### Parameters * `*args`: Variable length argument list. * `**kwargs`: Arbitrary keyword arguments. ### Returns None ``` -------------------------------- ### DetectionModel.check_dependencies Source: https://obss.github.io/sahi/api Checks if all necessary dependencies for the current model are installed. ```APIDOC ## DetectionModel.check_dependencies ### Description Verifies that all required libraries and packages for the loaded detection model are installed and accessible. ### Method `check_dependencies` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from sahi.auto_model import AutoDetectionModel # Load your detection model detection_model = AutoDetectionModel.from_pretrained( model_type='detectron2', model_path='path/to/model.pkl', image_size=640 ) # Check dependencies detection_model.check_dependencies() ``` ### Response #### Success Response (200) None. If all dependencies are met, the function completes without error. #### Response Example None #### Error Response Raises an `ImportError` or similar exception if a required dependency is missing. ``` -------------------------------- ### totensor Source: https://obss.github.io/sahi/postprocess/utils Converts the ObjectPredictionList to a torch.Tensor. Requires torch to be installed. ```APIDOC ## totensor() ### Description Convert to torch.Tensor. Requires torch to be installed. ### Returns - **object** - A torch.Tensor representation of the predictions. ### Source Code ```python def totensor(self) -> object: """Convert to torch.Tensor. Requires torch to be installed.""" return object_prediction_list_to_torch(self) ``` ``` -------------------------------- ### ObjectPredictionList.__init__ Source: https://obss.github.io/sahi/api Initialize the ObjectPredictionList with a list of object predictions. ```APIDOC ## __init__(prediction_list) ### Description Initialize with a list of object predictions. ### Parameters #### Path Parameters - **prediction_list** (list) - Required - List of ObjectPrediction instances. ### Returns None ``` -------------------------------- ### Initialize TorchVisionDetectionModel Source: https://obss.github.io/sahi/models/torchvision Initializes the TorchVision detection model, ensuring 'torch' and 'torchvision' are listed as required packages. ```python class TorchVisionDetectionModel(DetectionModel): """TorchVision object detection model. Supports various TorchVision detection models like Faster R-CNN, Mask R-CNN, etc. """ def __init__(self, *args: object, **kwargs: object) -> None: """Initialize TorchVision detection model.""" existing_packages = getattr(self, "required_packages", None) or [] self.required_packages = [*list(existing_packages), "torch", "torchvision"] super().__init__(*args, **kwargs) # type: ignore[misc, arg-type] ``` -------------------------------- ### ShapelyAnnotation.area Source: https://obss.github.io/sahi/api Gets the total area of all polygons within the annotation. ```APIDOC ## ShapelyAnnotation.area (property) ### Description Get the total area of all polygons. ### Returns - **int** - The total area of all polygons. ``` -------------------------------- ### CocoAnnotation.image_id Source: https://obss.github.io/sahi/api Gets or sets the image ID associated with the annotation. ```APIDOC ## CocoAnnotation.image_id ### Description Gets or sets the image id of the annotation. ### Property `image_id` (int | None) ### Setter `image_id(self, i: int) -> None` ### Setter Parameters #### Arguments - **i** (int) - The new image ID. Must be an integer. ``` -------------------------------- ### print_environment_info Source: https://obss.github.io/sahi/api Logs the version information for all commonly used SAHI dependency packages. ```APIDOC ## print_environment_info() ### Description Log version info for all commonly used SAHI dependency packages. ``` -------------------------------- ### __init__ Source: https://obss.github.io/sahi/prediction Initializes a PredictionResult object with detected objects, the source image, and optional duration information. ```APIDOC ## __init__ ### Description Initialize a PredictionResult. ### Parameters #### Path Parameters - **object_prediction_list** (list[ObjectPrediction]) - Required - list[ObjectPrediction] Detected objects for this image. - **image** (Image.Image | str | ndarray) - Required - Image.Image or str or np.ndarray The source image as a PIL Image, file path, or numpy array. #### Query Parameters - **durations_in_seconds** (dict[str, Any]) - Optional - dict[str, Any] Elapsed times for profiling (e.g. inference, postprocess). Default: dict() ``` -------------------------------- ### HuggingfaceDetectionModel.num_categories Source: https://obss.github.io/sahi/api Property to get the number of categories the model can detect. ```APIDOC ## num_categories ### Description Returns the number of categories the model is trained to detect. ### Returns - **num_categories** (int) - The total number of detectable categories. ```