Skip to content

roboflow

OnnxRoboflowCoreModel

Bases: RoboflowCoreModel

Roboflow Inference Model that operates using an ONNX model file.

Source code in inference/core/models/roboflow.py
831
832
833
834
class OnnxRoboflowCoreModel(RoboflowCoreModel):
    """Roboflow Inference Model that operates using an ONNX model file."""

    pass

OnnxRoboflowInferenceModel

Bases: RoboflowInferenceModel

Roboflow Inference Model that operates using an ONNX model file.

Source code in inference/core/models/roboflow.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
class OnnxRoboflowInferenceModel(RoboflowInferenceModel):
    """Roboflow Inference Model that operates using an ONNX model file."""

    def __init__(
        self,
        model_id: str,
        onnxruntime_execution_providers: List[
            str
        ] = get_onnxruntime_execution_providers(ONNXRUNTIME_EXECUTION_PROVIDERS),
        *args,
        **kwargs,
    ):
        """Initializes the OnnxRoboflowInferenceModel instance.

        Args:
            model_id (str): The identifier for the specific ONNX model.
            *args: Variable length argument list.
            **kwargs: Arbitrary keyword arguments.
        """
        super().__init__(model_id, *args, **kwargs)
        if self.load_weights or not self.has_model_metadata:
            self.onnxruntime_execution_providers = onnxruntime_execution_providers
            expanded_execution_providers = []
            for ep in self.onnxruntime_execution_providers:
                if ep == "TensorrtExecutionProvider":
                    ep = (
                        "TensorrtExecutionProvider",
                        {
                            "trt_engine_cache_enable": True,
                            "trt_engine_cache_path": os.path.join(
                                TENSORRT_CACHE_PATH, self.endpoint
                            ),
                            "trt_fp16_enable": True,
                        },
                    )
                expanded_execution_providers.append(ep)
            self.onnxruntime_execution_providers = expanded_execution_providers

        self.initialize_model()
        self.image_loader_threadpool = ThreadPoolExecutor(max_workers=None)
        try:
            self.validate_model()
        except ModelArtefactError as e:
            logger.error(f"Unable to validate model artifacts, clearing cache: {e}")
            self.clear_cache()
            raise ModelArtefactError from e

    def infer(self, image: Any, **kwargs) -> Any:
        """Runs inference on given data.
        - image:
            can be a BGR numpy array, filepath, InferenceRequestImage, PIL Image, byte-string, etc.
        """
        input_elements = len(image) if isinstance(image, list) else 1
        max_batch_size = MAX_BATCH_SIZE if self.batching_enabled else self.batch_size
        if (input_elements == 1) or (max_batch_size == float("inf")):
            return super().infer(image, **kwargs)
        logger.debug(
            f"Inference will be executed in batches, as there is {input_elements} input elements and "
            f"maximum batch size for a model is set to: {max_batch_size}"
        )
        inference_results = []
        for batch_input in create_batches(sequence=image, batch_size=max_batch_size):
            batch_inference_results = super().infer(batch_input, **kwargs)
            inference_results.append(batch_inference_results)
        return self.merge_inference_results(inference_results=inference_results)

    def merge_inference_results(self, inference_results: List[Any]) -> Any:
        return list(itertools.chain(*inference_results))

    def validate_model(self) -> None:
        if MODEL_VALIDATION_DISABLED:
            logger.debug("Model validation disabled.")
            return None
        logger.debug("Starting model validation")
        if not self.load_weights:
            return
        try:
            assert self.onnx_session is not None
        except AssertionError as e:
            raise ModelArtefactError(
                "ONNX session not initialized. Check that the model weights are available."
            ) from e
        try:
            self.run_test_inference()
        except Exception as e:
            raise ModelArtefactError(f"Unable to run test inference. Cause: {e}") from e
        try:
            self.validate_model_classes()
        except Exception as e:
            raise ModelArtefactError(
                f"Unable to validate model classes. Cause: {e}"
            ) from e
        logger.debug("Model validation finished")

    def run_test_inference(self) -> None:
        test_image = (np.random.rand(1024, 1024, 3) * 255).astype(np.uint8)
        logger.debug(f"Running test inference. Image size: {test_image.shape}")
        result = self.infer(test_image, usage_inference_test_run=True)
        logger.debug(f"Test inference finished.")
        return result

    def get_model_output_shape(self) -> Tuple[int, int, int]:
        test_image = (np.random.rand(1024, 1024, 3) * 255).astype(np.uint8)
        logger.debug(f"Getting model output shape. Image size: {test_image.shape}")
        test_image, _ = self.preprocess(test_image)
        output = self.predict(test_image)[0]
        logger.debug(f"Model output shape test finished.")
        return output.shape

    def validate_model_classes(self) -> None:
        pass

    def get_infer_bucket_file_list(self) -> list:
        """Returns the list of files to be downloaded from the inference bucket for ONNX model.

        Returns:
            list: A list of filenames specific to ONNX models.
        """
        return ["environment.json", "class_names.txt"]

    def initialize_model(self) -> None:
        """Initializes the ONNX model, setting up the inference session and other necessary properties."""
        logger.debug("Getting model artefacts")
        self.get_model_artifacts()
        logger.debug("Creating inference session")
        if self.load_weights or not self.has_model_metadata:
            t1_session = perf_counter()
            # Create an ONNX Runtime Session with a list of execution providers in priority order. ORT attempts to load providers until one is successful. This keeps the code across devices identical.
            providers = self.onnxruntime_execution_providers

            if not self.load_weights:
                providers = ["OpenVINOExecutionProvider", "CPUExecutionProvider"]
            try:
                session_options = onnxruntime.SessionOptions()
                # TensorRT does better graph optimization for its EP than onnx
                if has_trt(providers):
                    session_options.graph_optimization_level = (
                        onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
                    )
                self.onnx_session = onnxruntime.InferenceSession(
                    self.cache_file(self.weights_file),
                    providers=providers,
                    sess_options=session_options,
                )
            except Exception as e:
                self.clear_cache()
                raise ModelArtefactError(
                    f"Unable to load ONNX session. Cause: {e}"
                ) from e
            logger.debug(f"Session created in {perf_counter() - t1_session} seconds")

            if REQUIRED_ONNX_PROVIDERS:
                available_providers = onnxruntime.get_available_providers()
                for provider in REQUIRED_ONNX_PROVIDERS:
                    if provider not in available_providers:
                        raise OnnxProviderNotAvailable(
                            f"Required ONNX Execution Provider {provider} is not availble. "
                            "Check that you are using the correct docker image on a supported device. "
                            "Export list of available providers as ONNXRUNTIME_EXECUTION_PROVIDERS environmental variable, "
                            "consult documentation for more details."
                        )

            inputs = self.onnx_session.get_inputs()[0]
            input_shape = inputs.shape
            self.batch_size = input_shape[0]
            self.img_size_h = input_shape[2]
            self.img_size_w = input_shape[3]
            self.input_name = inputs.name
            if isinstance(self.img_size_h, str) or isinstance(self.img_size_w, str):
                if "resize" in self.preproc:
                    self.img_size_h = int(self.preproc["resize"]["height"])
                    self.img_size_w = int(self.preproc["resize"]["width"])
                else:
                    self.img_size_h = 640
                    self.img_size_w = 640

            if isinstance(self.batch_size, str):
                self.batching_enabled = True
                logger.debug(
                    f"Model {self.endpoint} is loaded with dynamic batching enabled"
                )
            else:
                self.batching_enabled = False
                logger.debug(
                    f"Model {self.endpoint} is loaded with dynamic batching disabled"
                )

            model_metadata = {
                "batch_size": self.batch_size,
                "img_size_h": self.img_size_h,
                "img_size_w": self.img_size_w,
            }
            logger.debug(f"Writing model metadata to memcache")
            self.write_model_metadata_to_memcache(model_metadata)
            if not self.load_weights:  # had to load weights to get metadata
                del self.onnx_session
        else:
            if not self.has_model_metadata:
                raise ValueError(
                    "This should be unreachable, should get weights if we don't have model metadata"
                )
            logger.debug(f"Loading model metadata from memcache")
            metadata = self.model_metadata_from_memcache()
            self.batch_size = metadata["batch_size"]
            self.img_size_h = metadata["img_size_h"]
            self.img_size_w = metadata["img_size_w"]
            if isinstance(self.batch_size, str):
                self.batching_enabled = True
                logger.debug(
                    f"Model {self.endpoint} is loaded with dynamic batching enabled"
                )
            else:
                self.batching_enabled = False
                logger.debug(
                    f"Model {self.endpoint} is loaded with dynamic batching disabled"
                )
        logger.debug("Model initialisation finished.")

    def load_image(
        self,
        image: Any,
        disable_preproc_auto_orient: bool = False,
        disable_preproc_contrast: bool = False,
        disable_preproc_grayscale: bool = False,
        disable_preproc_static_crop: bool = False,
    ) -> Tuple[np.ndarray, Tuple[int, int]]:
        if isinstance(image, list):
            preproc_image = partial(
                self.preproc_image,
                disable_preproc_auto_orient=disable_preproc_auto_orient,
                disable_preproc_contrast=disable_preproc_contrast,
                disable_preproc_grayscale=disable_preproc_grayscale,
                disable_preproc_static_crop=disable_preproc_static_crop,
            )
            imgs_with_dims = self.image_loader_threadpool.map(preproc_image, image)
            imgs, img_dims = zip(*imgs_with_dims)
            img_in = np.concatenate(imgs, axis=0)
        else:
            img_in, img_dims = self.preproc_image(
                image,
                disable_preproc_auto_orient=disable_preproc_auto_orient,
                disable_preproc_contrast=disable_preproc_contrast,
                disable_preproc_grayscale=disable_preproc_grayscale,
                disable_preproc_static_crop=disable_preproc_static_crop,
            )
            img_dims = [img_dims]
        return img_in, img_dims

    @property
    def weights_file(self) -> str:
        """Returns the file containing the ONNX model weights.

        Returns:
            str: The file path to the weights file.
        """
        return "weights.onnx"

weights_file: str property

Returns the file containing the ONNX model weights.

Returns:

Name Type Description
str str

The file path to the weights file.

__init__(model_id, onnxruntime_execution_providers=get_onnxruntime_execution_providers(ONNXRUNTIME_EXECUTION_PROVIDERS), *args, **kwargs)

Initializes the OnnxRoboflowInferenceModel instance.

Parameters:

Name Type Description Default
model_id str

The identifier for the specific ONNX model.

required
*args

Variable length argument list.

()
**kwargs

Arbitrary keyword arguments.

{}
Source code in inference/core/models/roboflow.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def __init__(
    self,
    model_id: str,
    onnxruntime_execution_providers: List[
        str
    ] = get_onnxruntime_execution_providers(ONNXRUNTIME_EXECUTION_PROVIDERS),
    *args,
    **kwargs,
):
    """Initializes the OnnxRoboflowInferenceModel instance.

    Args:
        model_id (str): The identifier for the specific ONNX model.
        *args: Variable length argument list.
        **kwargs: Arbitrary keyword arguments.
    """
    super().__init__(model_id, *args, **kwargs)
    if self.load_weights or not self.has_model_metadata:
        self.onnxruntime_execution_providers = onnxruntime_execution_providers
        expanded_execution_providers = []
        for ep in self.onnxruntime_execution_providers:
            if ep == "TensorrtExecutionProvider":
                ep = (
                    "TensorrtExecutionProvider",
                    {
                        "trt_engine_cache_enable": True,
                        "trt_engine_cache_path": os.path.join(
                            TENSORRT_CACHE_PATH, self.endpoint
                        ),
                        "trt_fp16_enable": True,
                    },
                )
            expanded_execution_providers.append(ep)
        self.onnxruntime_execution_providers = expanded_execution_providers

    self.initialize_model()
    self.image_loader_threadpool = ThreadPoolExecutor(max_workers=None)
    try:
        self.validate_model()
    except ModelArtefactError as e:
        logger.error(f"Unable to validate model artifacts, clearing cache: {e}")
        self.clear_cache()
        raise ModelArtefactError from e

get_infer_bucket_file_list()

Returns the list of files to be downloaded from the inference bucket for ONNX model.

Returns:

Name Type Description
list list

A list of filenames specific to ONNX models.

Source code in inference/core/models/roboflow.py
685
686
687
688
689
690
691
def get_infer_bucket_file_list(self) -> list:
    """Returns the list of files to be downloaded from the inference bucket for ONNX model.

    Returns:
        list: A list of filenames specific to ONNX models.
    """
    return ["environment.json", "class_names.txt"]

infer(image, **kwargs)

Runs inference on given data. - image: can be a BGR numpy array, filepath, InferenceRequestImage, PIL Image, byte-string, etc.

Source code in inference/core/models/roboflow.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def infer(self, image: Any, **kwargs) -> Any:
    """Runs inference on given data.
    - image:
        can be a BGR numpy array, filepath, InferenceRequestImage, PIL Image, byte-string, etc.
    """
    input_elements = len(image) if isinstance(image, list) else 1
    max_batch_size = MAX_BATCH_SIZE if self.batching_enabled else self.batch_size
    if (input_elements == 1) or (max_batch_size == float("inf")):
        return super().infer(image, **kwargs)
    logger.debug(
        f"Inference will be executed in batches, as there is {input_elements} input elements and "
        f"maximum batch size for a model is set to: {max_batch_size}"
    )
    inference_results = []
    for batch_input in create_batches(sequence=image, batch_size=max_batch_size):
        batch_inference_results = super().infer(batch_input, **kwargs)
        inference_results.append(batch_inference_results)
    return self.merge_inference_results(inference_results=inference_results)

initialize_model()

Initializes the ONNX model, setting up the inference session and other necessary properties.

Source code in inference/core/models/roboflow.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
def initialize_model(self) -> None:
    """Initializes the ONNX model, setting up the inference session and other necessary properties."""
    logger.debug("Getting model artefacts")
    self.get_model_artifacts()
    logger.debug("Creating inference session")
    if self.load_weights or not self.has_model_metadata:
        t1_session = perf_counter()
        # Create an ONNX Runtime Session with a list of execution providers in priority order. ORT attempts to load providers until one is successful. This keeps the code across devices identical.
        providers = self.onnxruntime_execution_providers

        if not self.load_weights:
            providers = ["OpenVINOExecutionProvider", "CPUExecutionProvider"]
        try:
            session_options = onnxruntime.SessionOptions()
            # TensorRT does better graph optimization for its EP than onnx
            if has_trt(providers):
                session_options.graph_optimization_level = (
                    onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
                )
            self.onnx_session = onnxruntime.InferenceSession(
                self.cache_file(self.weights_file),
                providers=providers,
                sess_options=session_options,
            )
        except Exception as e:
            self.clear_cache()
            raise ModelArtefactError(
                f"Unable to load ONNX session. Cause: {e}"
            ) from e
        logger.debug(f"Session created in {perf_counter() - t1_session} seconds")

        if REQUIRED_ONNX_PROVIDERS:
            available_providers = onnxruntime.get_available_providers()
            for provider in REQUIRED_ONNX_PROVIDERS:
                if provider not in available_providers:
                    raise OnnxProviderNotAvailable(
                        f"Required ONNX Execution Provider {provider} is not availble. "
                        "Check that you are using the correct docker image on a supported device. "
                        "Export list of available providers as ONNXRUNTIME_EXECUTION_PROVIDERS environmental variable, "
                        "consult documentation for more details."
                    )

        inputs = self.onnx_session.get_inputs()[0]
        input_shape = inputs.shape
        self.batch_size = input_shape[0]
        self.img_size_h = input_shape[2]
        self.img_size_w = input_shape[3]
        self.input_name = inputs.name
        if isinstance(self.img_size_h, str) or isinstance(self.img_size_w, str):
            if "resize" in self.preproc:
                self.img_size_h = int(self.preproc["resize"]["height"])
                self.img_size_w = int(self.preproc["resize"]["width"])
            else:
                self.img_size_h = 640
                self.img_size_w = 640

        if isinstance(self.batch_size, str):
            self.batching_enabled = True
            logger.debug(
                f"Model {self.endpoint} is loaded with dynamic batching enabled"
            )
        else:
            self.batching_enabled = False
            logger.debug(
                f"Model {self.endpoint} is loaded with dynamic batching disabled"
            )

        model_metadata = {
            "batch_size": self.batch_size,
            "img_size_h": self.img_size_h,
            "img_size_w": self.img_size_w,
        }
        logger.debug(f"Writing model metadata to memcache")
        self.write_model_metadata_to_memcache(model_metadata)
        if not self.load_weights:  # had to load weights to get metadata
            del self.onnx_session
    else:
        if not self.has_model_metadata:
            raise ValueError(
                "This should be unreachable, should get weights if we don't have model metadata"
            )
        logger.debug(f"Loading model metadata from memcache")
        metadata = self.model_metadata_from_memcache()
        self.batch_size = metadata["batch_size"]
        self.img_size_h = metadata["img_size_h"]
        self.img_size_w = metadata["img_size_w"]
        if isinstance(self.batch_size, str):
            self.batching_enabled = True
            logger.debug(
                f"Model {self.endpoint} is loaded with dynamic batching enabled"
            )
        else:
            self.batching_enabled = False
            logger.debug(
                f"Model {self.endpoint} is loaded with dynamic batching disabled"
            )
    logger.debug("Model initialisation finished.")

RoboflowCoreModel

Bases: RoboflowInferenceModel

Base Roboflow inference model (Inherits from CvModel since all Roboflow models are CV models currently).

Source code in inference/core/models/roboflow.py
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
class RoboflowCoreModel(RoboflowInferenceModel):
    """Base Roboflow inference model (Inherits from CvModel since all Roboflow models are CV models currently)."""

    def __init__(
        self,
        model_id: str,
        api_key=None,
    ):
        """Initializes the RoboflowCoreModel instance.

        Args:
            model_id (str): The identifier for the specific model.
            api_key ([type], optional): The API key for authentication. Defaults to None.
        """
        super().__init__(model_id, api_key=api_key)
        self.download_weights()

    def download_weights(self) -> None:
        """Downloads the model weights from the configured source.

        This method includes handling for AWS access keys and error handling.
        """
        infer_bucket_files = self.get_infer_bucket_file_list()
        if are_all_files_cached(files=infer_bucket_files, model_id=self.endpoint):
            logger.debug("Model artifacts already downloaded, loading from cache")
            return None
        if is_model_artefacts_bucket_available():
            self.download_model_artefacts_from_s3()
            return None
        self.download_model_from_roboflow_api()

    def download_model_from_roboflow_api(self) -> None:
        api_data = get_roboflow_model_data(
            api_key=self.api_key,
            model_id=self.endpoint,
            endpoint_type=ModelEndpointType.CORE_MODEL,
            device_id=self.device_id,
        )
        if "weights" not in api_data:
            raise ModelArtefactError(
                f"`weights` key not available in Roboflow API response while downloading model weights."
            )
        for weights_url_key in api_data["weights"]:
            weights_url = api_data["weights"][weights_url_key]
            t1 = perf_counter()
            model_weights_response = get_from_url(weights_url, json_response=False)
            filename = weights_url.split("?")[0].split("/")[-1]
            save_bytes_in_cache(
                content=model_weights_response.content,
                file=filename,
                model_id=self.endpoint,
            )
            if perf_counter() - t1 > 120:
                logger.debug(
                    "Weights download took longer than 120 seconds, refreshing API request"
                )
                api_data = get_roboflow_model_data(
                    api_key=self.api_key,
                    model_id=self.endpoint,
                    endpoint_type=ModelEndpointType.CORE_MODEL,
                    device_id=self.device_id,
                )

    def get_device_id(self) -> str:
        """Returns the device ID associated with this model.

        Returns:
            str: The device ID.
        """
        return self.device_id

    def get_infer_bucket_file_list(self) -> List[str]:
        """Abstract method to get the list of files to be downloaded from the inference bucket.

        Raises:
            NotImplementedError: This method must be implemented in subclasses.

        Returns:
            List[str]: A list of filenames.
        """
        raise NotImplementedError(
            "get_infer_bucket_file_list not implemented for OnnxRoboflowCoreModel"
        )

    def preprocess_image(self, image: Image.Image) -> Image.Image:
        """Abstract method to preprocess an image.

        Raises:
            NotImplementedError: This method must be implemented in subclasses.

        Returns:
            Image.Image: The preprocessed PIL image.
        """
        raise NotImplementedError(self.__class__.__name__ + ".preprocess_image")

    @property
    def weights_file(self) -> str:
        """Abstract property representing the file containing the model weights. For core models, all model artifacts are handled through get_infer_bucket_file_list method."""
        return None

    @property
    def model_artifact_bucket(self):
        return CORE_MODEL_BUCKET

weights_file: str property

Abstract property representing the file containing the model weights. For core models, all model artifacts are handled through get_infer_bucket_file_list method.

__init__(model_id, api_key=None)

Initializes the RoboflowCoreModel instance.

Parameters:

Name Type Description Default
model_id str

The identifier for the specific model.

required
api_key [type]

The API key for authentication. Defaults to None.

None
Source code in inference/core/models/roboflow.py
471
472
473
474
475
476
477
478
479
480
481
482
483
def __init__(
    self,
    model_id: str,
    api_key=None,
):
    """Initializes the RoboflowCoreModel instance.

    Args:
        model_id (str): The identifier for the specific model.
        api_key ([type], optional): The API key for authentication. Defaults to None.
    """
    super().__init__(model_id, api_key=api_key)
    self.download_weights()

download_weights()

Downloads the model weights from the configured source.

This method includes handling for AWS access keys and error handling.

Source code in inference/core/models/roboflow.py
485
486
487
488
489
490
491
492
493
494
495
496
497
def download_weights(self) -> None:
    """Downloads the model weights from the configured source.

    This method includes handling for AWS access keys and error handling.
    """
    infer_bucket_files = self.get_infer_bucket_file_list()
    if are_all_files_cached(files=infer_bucket_files, model_id=self.endpoint):
        logger.debug("Model artifacts already downloaded, loading from cache")
        return None
    if is_model_artefacts_bucket_available():
        self.download_model_artefacts_from_s3()
        return None
    self.download_model_from_roboflow_api()

get_device_id()

Returns the device ID associated with this model.

Returns:

Name Type Description
str str

The device ID.

Source code in inference/core/models/roboflow.py
531
532
533
534
535
536
537
def get_device_id(self) -> str:
    """Returns the device ID associated with this model.

    Returns:
        str: The device ID.
    """
    return self.device_id

get_infer_bucket_file_list()

Abstract method to get the list of files to be downloaded from the inference bucket.

Raises:

Type Description
NotImplementedError

This method must be implemented in subclasses.

Returns:

Type Description
List[str]

List[str]: A list of filenames.

Source code in inference/core/models/roboflow.py
539
540
541
542
543
544
545
546
547
548
549
550
def get_infer_bucket_file_list(self) -> List[str]:
    """Abstract method to get the list of files to be downloaded from the inference bucket.

    Raises:
        NotImplementedError: This method must be implemented in subclasses.

    Returns:
        List[str]: A list of filenames.
    """
    raise NotImplementedError(
        "get_infer_bucket_file_list not implemented for OnnxRoboflowCoreModel"
    )

preprocess_image(image)

Abstract method to preprocess an image.

Raises:

Type Description
NotImplementedError

This method must be implemented in subclasses.

Returns:

Type Description
Image

Image.Image: The preprocessed PIL image.

Source code in inference/core/models/roboflow.py
552
553
554
555
556
557
558
559
560
561
def preprocess_image(self, image: Image.Image) -> Image.Image:
    """Abstract method to preprocess an image.

    Raises:
        NotImplementedError: This method must be implemented in subclasses.

    Returns:
        Image.Image: The preprocessed PIL image.
    """
    raise NotImplementedError(self.__class__.__name__ + ".preprocess_image")

RoboflowInferenceModel

Bases: Model

Base Roboflow inference model.

Source code in inference/core/models/roboflow.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
class RoboflowInferenceModel(Model):
    """Base Roboflow inference model."""

    def __init__(
        self,
        model_id: str,
        cache_dir_root=MODEL_CACHE_DIR,
        api_key=None,
        load_weights=True,
    ):
        """
        Initialize the RoboflowInferenceModel object.

        Args:
            model_id (str): The unique identifier for the model.
            cache_dir_root (str, optional): The root directory for the cache. Defaults to MODEL_CACHE_DIR.
            api_key (str, optional): API key for authentication. Defaults to None.
        """
        super().__init__()
        self.load_weights = load_weights
        self.metrics = {"num_inferences": 0, "avg_inference_time": 0.0}
        self.api_key = api_key if api_key else API_KEY
        model_id = resolve_roboflow_model_alias(model_id=model_id)
        self.dataset_id, self.version_id = model_id.split("/")
        self.endpoint = model_id
        self.device_id = GLOBAL_DEVICE_ID
        self.cache_dir = os.path.join(cache_dir_root, self.endpoint)
        self.keypoints_metadata: Optional[dict] = None
        initialise_cache(model_id=self.endpoint)

    def cache_file(self, f: str) -> str:
        """Get the cache file path for a given file.

        Args:
            f (str): Filename.

        Returns:
            str: Full path to the cached file.
        """
        return get_cache_file_path(file=f, model_id=self.endpoint)

    def clear_cache(self) -> None:
        """Clear the cache directory."""
        clear_cache(model_id=self.endpoint)

    def draw_predictions(
        self,
        inference_request: InferenceRequest,
        inference_response: InferenceResponse,
    ) -> bytes:
        """Draw predictions from an inference response onto the original image provided by an inference request

        Args:
            inference_request (ObjectDetectionInferenceRequest): The inference request containing the image on which to draw predictions
            inference_response (ObjectDetectionInferenceResponse): The inference response containing predictions to be drawn

        Returns:
            str: A base64 encoded image string
        """
        return draw_detection_predictions(
            inference_request=inference_request,
            inference_response=inference_response,
            colors=self.colors,
        )

    @property
    def get_class_names(self):
        return self.class_names

    def get_device_id(self) -> str:
        """
        Get the device identifier on which the model is deployed.

        Returns:
            str: Device identifier.
        """
        return self.device_id

    def get_infer_bucket_file_list(self) -> List[str]:
        """Get a list of inference bucket files.

        Raises:
            NotImplementedError: If the method is not implemented.

        Returns:
            List[str]: A list of inference bucket files.
        """
        raise NotImplementedError(
            self.__class__.__name__ + ".get_infer_bucket_file_list"
        )

    @property
    def cache_key(self):
        return f"metadata:{self.endpoint}"

    @staticmethod
    def model_metadata_from_memcache_endpoint(endpoint):
        model_metadata = cache.get(f"metadata:{endpoint}")
        return model_metadata

    def model_metadata_from_memcache(self):
        model_metadata = cache.get(self.cache_key)
        return model_metadata

    def write_model_metadata_to_memcache(self, metadata):
        cache.set(
            self.cache_key, metadata, expire=MODEL_METADATA_CACHE_EXPIRATION_TIMEOUT
        )

    @property
    def has_model_metadata(self):
        return self.model_metadata_from_memcache() is not None

    def get_model_artifacts(self) -> None:
        """Fetch or load the model artifacts.

        Downloads the model artifacts from S3 or the Roboflow API if they are not already cached.
        """
        self.cache_model_artefacts()
        self.load_model_artifacts_from_cache()

    def cache_model_artefacts(self) -> None:
        infer_bucket_files = self.get_all_required_infer_bucket_file()
        if are_all_files_cached(files=infer_bucket_files, model_id=self.endpoint):
            return None
        if is_model_artefacts_bucket_available():
            self.download_model_artefacts_from_s3()
            return None
        self.download_model_artifacts_from_roboflow_api()

    def get_all_required_infer_bucket_file(self) -> List[str]:
        infer_bucket_files = self.get_infer_bucket_file_list()
        infer_bucket_files.append(self.weights_file)
        logger.debug(f"List of files required to load model: {infer_bucket_files}")
        return [f for f in infer_bucket_files if f is not None]

    def download_model_artefacts_from_s3(self) -> None:
        try:
            logger.debug("Downloading model artifacts from S3")
            infer_bucket_files = self.get_all_required_infer_bucket_file()
            cache_directory = get_cache_dir()
            s3_keys = [f"{self.endpoint}/{file}" for file in infer_bucket_files]
            download_s3_files_to_directory(
                bucket=self.model_artifact_bucket,
                keys=s3_keys,
                target_dir=cache_directory,
                s3_client=S3_CLIENT,
            )
        except Exception as error:
            raise ModelArtefactError(
                f"Could not obtain model artefacts from S3 with keys {s3_keys}. Cause: {error}"
            ) from error

    @property
    def model_artifact_bucket(self):
        return INFER_BUCKET

    def download_model_artifacts_from_roboflow_api(self) -> None:
        logger.debug("Downloading model artifacts from Roboflow API")
        api_data = get_roboflow_model_data(
            api_key=self.api_key,
            model_id=self.endpoint,
            endpoint_type=ModelEndpointType.ORT,
            device_id=self.device_id,
        )
        if "ort" not in api_data.keys():
            raise ModelArtefactError(
                "Could not find `ort` key in roboflow API model description response."
            )
        api_data = api_data["ort"]
        if "classes" in api_data:
            save_text_lines_in_cache(
                content=api_data["classes"],
                file="class_names.txt",
                model_id=self.endpoint,
            )
        if "model" not in api_data:
            raise ModelArtefactError(
                "Could not find `model` key in roboflow API model description response."
            )
        if "environment" not in api_data:
            raise ModelArtefactError(
                "Could not find `environment` key in roboflow API model description response."
            )
        environment = get_from_url(api_data["environment"])
        model_weights_response = get_from_url(api_data["model"], json_response=False)
        save_bytes_in_cache(
            content=model_weights_response.content,
            file=self.weights_file,
            model_id=self.endpoint,
        )
        if "colors" in api_data:
            environment["COLORS"] = api_data["colors"]
        save_json_in_cache(
            content=environment,
            file="environment.json",
            model_id=self.endpoint,
        )
        if "keypoints_metadata" in api_data:
            # TODO: make sure backend provides that
            save_json_in_cache(
                content=api_data["keypoints_metadata"],
                file="keypoints_metadata.json",
                model_id=self.endpoint,
            )

    def load_model_artifacts_from_cache(self) -> None:
        logger.debug("Model artifacts already downloaded, loading model from cache")
        infer_bucket_files = self.get_all_required_infer_bucket_file()
        if "environment.json" in infer_bucket_files:
            self.environment = load_json_from_cache(
                file="environment.json",
                model_id=self.endpoint,
                object_pairs_hook=OrderedDict,
            )
        if "class_names.txt" in infer_bucket_files:
            self.class_names = load_text_file_from_cache(
                file="class_names.txt",
                model_id=self.endpoint,
                split_lines=True,
                strip_white_chars=True,
            )
        else:
            self.class_names = get_class_names_from_environment_file(
                environment=self.environment
            )
        self.colors = get_color_mapping_from_environment(
            environment=self.environment,
            class_names=self.class_names,
        )
        if "keypoints_metadata.json" in infer_bucket_files:
            self.keypoints_metadata = parse_keypoints_metadata(
                load_json_from_cache(
                    file="keypoints_metadata.json",
                    model_id=self.endpoint,
                    object_pairs_hook=OrderedDict,
                )
            )
        self.num_classes = len(self.class_names)
        if "PREPROCESSING" not in self.environment:
            raise ModelArtefactError(
                "Could not find `PREPROCESSING` key in environment file."
            )
        if issubclass(type(self.environment["PREPROCESSING"]), dict):
            self.preproc = self.environment["PREPROCESSING"]
        else:
            self.preproc = json.loads(self.environment["PREPROCESSING"])
        if self.preproc.get("resize"):
            self.resize_method = self.preproc["resize"].get("format", "Stretch to")
            if self.resize_method not in [
                "Stretch to",
                "Fit (black edges) in",
                "Fit (white edges) in",
                "Fit (grey edges) in",
            ]:
                self.resize_method = "Stretch to"
        else:
            self.resize_method = "Stretch to"
        logger.debug(f"Resize method is '{self.resize_method}'")
        self.multiclass = self.environment.get("MULTICLASS", False)

    def initialize_model(self) -> None:
        """Initialize the model.

        Raises:
            NotImplementedError: If the method is not implemented.
        """
        raise NotImplementedError(self.__class__.__name__ + ".initialize_model")

    def preproc_image(
        self,
        image: Union[Any, InferenceRequestImage],
        disable_preproc_auto_orient: bool = False,
        disable_preproc_contrast: bool = False,
        disable_preproc_grayscale: bool = False,
        disable_preproc_static_crop: bool = False,
    ) -> Tuple[np.ndarray, Tuple[int, int]]:
        """
        Preprocesses an inference request image by loading it, then applying any pre-processing specified by the Roboflow platform, then scaling it to the inference input dimensions.

        Args:
            image (Union[Any, InferenceRequestImage]): An object containing information necessary to load the image for inference.
            disable_preproc_auto_orient (bool, optional): If true, the auto orient preprocessing step is disabled for this call. Default is False.
            disable_preproc_contrast (bool, optional): If true, the contrast preprocessing step is disabled for this call. Default is False.
            disable_preproc_grayscale (bool, optional): If true, the grayscale preprocessing step is disabled for this call. Default is False.
            disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.

        Returns:
            Tuple[np.ndarray, Tuple[int, int]]: A tuple containing a numpy array of the preprocessed image pixel data and a tuple of the images original size.
        """
        np_image, is_bgr = load_image(
            image,
            disable_preproc_auto_orient=disable_preproc_auto_orient
            or "auto-orient" not in self.preproc.keys()
            or DISABLE_PREPROC_AUTO_ORIENT,
        )
        preprocessed_image, img_dims = self.preprocess_image(
            np_image,
            disable_preproc_contrast=disable_preproc_contrast,
            disable_preproc_grayscale=disable_preproc_grayscale,
            disable_preproc_static_crop=disable_preproc_static_crop,
        )

        if self.resize_method == "Stretch to":
            resized = cv2.resize(
                preprocessed_image, (self.img_size_w, self.img_size_h), cv2.INTER_CUBIC
            )
        elif self.resize_method == "Fit (black edges) in":
            resized = letterbox_image(
                preprocessed_image, (self.img_size_w, self.img_size_h)
            )
        elif self.resize_method == "Fit (white edges) in":
            resized = letterbox_image(
                preprocessed_image,
                (self.img_size_w, self.img_size_h),
                color=(255, 255, 255),
            )
        elif self.resize_method == "Fit (grey edges) in":
            resized = letterbox_image(
                preprocessed_image,
                (self.img_size_w, self.img_size_h),
                color=(114, 114, 114),
            )

        if is_bgr:
            resized = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
        img_in = np.transpose(resized, (2, 0, 1))
        img_in = img_in.astype(np.float32)
        img_in = np.expand_dims(img_in, axis=0)

        return img_in, img_dims

    def preprocess_image(
        self,
        image: np.ndarray,
        disable_preproc_contrast: bool = False,
        disable_preproc_grayscale: bool = False,
        disable_preproc_static_crop: bool = False,
    ) -> Tuple[np.ndarray, Tuple[int, int]]:
        """
        Preprocesses the given image using specified preprocessing steps.

        Args:
            image (Image.Image): The PIL image to preprocess.
            disable_preproc_contrast (bool, optional): If true, the contrast preprocessing step is disabled for this call. Default is False.
            disable_preproc_grayscale (bool, optional): If true, the grayscale preprocessing step is disabled for this call. Default is False.
            disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.

        Returns:
            Image.Image: The preprocessed PIL image.
        """
        return prepare(
            image,
            self.preproc,
            disable_preproc_contrast=disable_preproc_contrast,
            disable_preproc_grayscale=disable_preproc_grayscale,
            disable_preproc_static_crop=disable_preproc_static_crop,
        )

    @property
    def weights_file(self) -> str:
        """Abstract property representing the file containing the model weights.

        Raises:
            NotImplementedError: This property must be implemented in subclasses.

        Returns:
            str: The file path to the weights file.
        """
        raise NotImplementedError(self.__class__.__name__ + ".weights_file")

weights_file: str property

Abstract property representing the file containing the model weights.

Raises:

Type Description
NotImplementedError

This property must be implemented in subclasses.

Returns:

Name Type Description
str str

The file path to the weights file.

__init__(model_id, cache_dir_root=MODEL_CACHE_DIR, api_key=None, load_weights=True)

Initialize the RoboflowInferenceModel object.

Parameters:

Name Type Description Default
model_id str

The unique identifier for the model.

required
cache_dir_root str

The root directory for the cache. Defaults to MODEL_CACHE_DIR.

MODEL_CACHE_DIR
api_key str

API key for authentication. Defaults to None.

None
Source code in inference/core/models/roboflow.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def __init__(
    self,
    model_id: str,
    cache_dir_root=MODEL_CACHE_DIR,
    api_key=None,
    load_weights=True,
):
    """
    Initialize the RoboflowInferenceModel object.

    Args:
        model_id (str): The unique identifier for the model.
        cache_dir_root (str, optional): The root directory for the cache. Defaults to MODEL_CACHE_DIR.
        api_key (str, optional): API key for authentication. Defaults to None.
    """
    super().__init__()
    self.load_weights = load_weights
    self.metrics = {"num_inferences": 0, "avg_inference_time": 0.0}
    self.api_key = api_key if api_key else API_KEY
    model_id = resolve_roboflow_model_alias(model_id=model_id)
    self.dataset_id, self.version_id = model_id.split("/")
    self.endpoint = model_id
    self.device_id = GLOBAL_DEVICE_ID
    self.cache_dir = os.path.join(cache_dir_root, self.endpoint)
    self.keypoints_metadata: Optional[dict] = None
    initialise_cache(model_id=self.endpoint)

cache_file(f)

Get the cache file path for a given file.

Parameters:

Name Type Description Default
f str

Filename.

required

Returns:

Name Type Description
str str

Full path to the cached file.

Source code in inference/core/models/roboflow.py
126
127
128
129
130
131
132
133
134
135
def cache_file(self, f: str) -> str:
    """Get the cache file path for a given file.

    Args:
        f (str): Filename.

    Returns:
        str: Full path to the cached file.
    """
    return get_cache_file_path(file=f, model_id=self.endpoint)

clear_cache()

Clear the cache directory.

Source code in inference/core/models/roboflow.py
137
138
139
def clear_cache(self) -> None:
    """Clear the cache directory."""
    clear_cache(model_id=self.endpoint)

draw_predictions(inference_request, inference_response)

Draw predictions from an inference response onto the original image provided by an inference request

Parameters:

Name Type Description Default
inference_request ObjectDetectionInferenceRequest

The inference request containing the image on which to draw predictions

required
inference_response ObjectDetectionInferenceResponse

The inference response containing predictions to be drawn

required

Returns:

Name Type Description
str bytes

A base64 encoded image string

Source code in inference/core/models/roboflow.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def draw_predictions(
    self,
    inference_request: InferenceRequest,
    inference_response: InferenceResponse,
) -> bytes:
    """Draw predictions from an inference response onto the original image provided by an inference request

    Args:
        inference_request (ObjectDetectionInferenceRequest): The inference request containing the image on which to draw predictions
        inference_response (ObjectDetectionInferenceResponse): The inference response containing predictions to be drawn

    Returns:
        str: A base64 encoded image string
    """
    return draw_detection_predictions(
        inference_request=inference_request,
        inference_response=inference_response,
        colors=self.colors,
    )

get_device_id()

Get the device identifier on which the model is deployed.

Returns:

Name Type Description
str str

Device identifier.

Source code in inference/core/models/roboflow.py
165
166
167
168
169
170
171
172
def get_device_id(self) -> str:
    """
    Get the device identifier on which the model is deployed.

    Returns:
        str: Device identifier.
    """
    return self.device_id

get_infer_bucket_file_list()

Get a list of inference bucket files.

Raises:

Type Description
NotImplementedError

If the method is not implemented.

Returns:

Type Description
List[str]

List[str]: A list of inference bucket files.

Source code in inference/core/models/roboflow.py
174
175
176
177
178
179
180
181
182
183
184
185
def get_infer_bucket_file_list(self) -> List[str]:
    """Get a list of inference bucket files.

    Raises:
        NotImplementedError: If the method is not implemented.

    Returns:
        List[str]: A list of inference bucket files.
    """
    raise NotImplementedError(
        self.__class__.__name__ + ".get_infer_bucket_file_list"
    )

get_model_artifacts()

Fetch or load the model artifacts.

Downloads the model artifacts from S3 or the Roboflow API if they are not already cached.

Source code in inference/core/models/roboflow.py
209
210
211
212
213
214
215
def get_model_artifacts(self) -> None:
    """Fetch or load the model artifacts.

    Downloads the model artifacts from S3 or the Roboflow API if they are not already cached.
    """
    self.cache_model_artefacts()
    self.load_model_artifacts_from_cache()

initialize_model()

Initialize the model.

Raises:

Type Description
NotImplementedError

If the method is not implemented.

Source code in inference/core/models/roboflow.py
357
358
359
360
361
362
363
def initialize_model(self) -> None:
    """Initialize the model.

    Raises:
        NotImplementedError: If the method is not implemented.
    """
    raise NotImplementedError(self.__class__.__name__ + ".initialize_model")

preproc_image(image, disable_preproc_auto_orient=False, disable_preproc_contrast=False, disable_preproc_grayscale=False, disable_preproc_static_crop=False)

Preprocesses an inference request image by loading it, then applying any pre-processing specified by the Roboflow platform, then scaling it to the inference input dimensions.

Parameters:

Name Type Description Default
image Union[Any, InferenceRequestImage]

An object containing information necessary to load the image for inference.

required
disable_preproc_auto_orient bool

If true, the auto orient preprocessing step is disabled for this call. Default is False.

False
disable_preproc_contrast bool

If true, the contrast preprocessing step is disabled for this call. Default is False.

False
disable_preproc_grayscale bool

If true, the grayscale preprocessing step is disabled for this call. Default is False.

False
disable_preproc_static_crop bool

If true, the static crop preprocessing step is disabled for this call. Default is False.

False

Returns:

Type Description
Tuple[ndarray, Tuple[int, int]]

Tuple[np.ndarray, Tuple[int, int]]: A tuple containing a numpy array of the preprocessed image pixel data and a tuple of the images original size.

Source code in inference/core/models/roboflow.py
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def preproc_image(
    self,
    image: Union[Any, InferenceRequestImage],
    disable_preproc_auto_orient: bool = False,
    disable_preproc_contrast: bool = False,
    disable_preproc_grayscale: bool = False,
    disable_preproc_static_crop: bool = False,
) -> Tuple[np.ndarray, Tuple[int, int]]:
    """
    Preprocesses an inference request image by loading it, then applying any pre-processing specified by the Roboflow platform, then scaling it to the inference input dimensions.

    Args:
        image (Union[Any, InferenceRequestImage]): An object containing information necessary to load the image for inference.
        disable_preproc_auto_orient (bool, optional): If true, the auto orient preprocessing step is disabled for this call. Default is False.
        disable_preproc_contrast (bool, optional): If true, the contrast preprocessing step is disabled for this call. Default is False.
        disable_preproc_grayscale (bool, optional): If true, the grayscale preprocessing step is disabled for this call. Default is False.
        disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.

    Returns:
        Tuple[np.ndarray, Tuple[int, int]]: A tuple containing a numpy array of the preprocessed image pixel data and a tuple of the images original size.
    """
    np_image, is_bgr = load_image(
        image,
        disable_preproc_auto_orient=disable_preproc_auto_orient
        or "auto-orient" not in self.preproc.keys()
        or DISABLE_PREPROC_AUTO_ORIENT,
    )
    preprocessed_image, img_dims = self.preprocess_image(
        np_image,
        disable_preproc_contrast=disable_preproc_contrast,
        disable_preproc_grayscale=disable_preproc_grayscale,
        disable_preproc_static_crop=disable_preproc_static_crop,
    )

    if self.resize_method == "Stretch to":
        resized = cv2.resize(
            preprocessed_image, (self.img_size_w, self.img_size_h), cv2.INTER_CUBIC
        )
    elif self.resize_method == "Fit (black edges) in":
        resized = letterbox_image(
            preprocessed_image, (self.img_size_w, self.img_size_h)
        )
    elif self.resize_method == "Fit (white edges) in":
        resized = letterbox_image(
            preprocessed_image,
            (self.img_size_w, self.img_size_h),
            color=(255, 255, 255),
        )
    elif self.resize_method == "Fit (grey edges) in":
        resized = letterbox_image(
            preprocessed_image,
            (self.img_size_w, self.img_size_h),
            color=(114, 114, 114),
        )

    if is_bgr:
        resized = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB)
    img_in = np.transpose(resized, (2, 0, 1))
    img_in = img_in.astype(np.float32)
    img_in = np.expand_dims(img_in, axis=0)

    return img_in, img_dims

preprocess_image(image, disable_preproc_contrast=False, disable_preproc_grayscale=False, disable_preproc_static_crop=False)

Preprocesses the given image using specified preprocessing steps.

Parameters:

Name Type Description Default
image Image

The PIL image to preprocess.

required
disable_preproc_contrast bool

If true, the contrast preprocessing step is disabled for this call. Default is False.

False
disable_preproc_grayscale bool

If true, the grayscale preprocessing step is disabled for this call. Default is False.

False
disable_preproc_static_crop bool

If true, the static crop preprocessing step is disabled for this call. Default is False.

False

Returns:

Type Description
Tuple[ndarray, Tuple[int, int]]

Image.Image: The preprocessed PIL image.

Source code in inference/core/models/roboflow.py
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def preprocess_image(
    self,
    image: np.ndarray,
    disable_preproc_contrast: bool = False,
    disable_preproc_grayscale: bool = False,
    disable_preproc_static_crop: bool = False,
) -> Tuple[np.ndarray, Tuple[int, int]]:
    """
    Preprocesses the given image using specified preprocessing steps.

    Args:
        image (Image.Image): The PIL image to preprocess.
        disable_preproc_contrast (bool, optional): If true, the contrast preprocessing step is disabled for this call. Default is False.
        disable_preproc_grayscale (bool, optional): If true, the grayscale preprocessing step is disabled for this call. Default is False.
        disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.

    Returns:
        Image.Image: The preprocessed PIL image.
    """
    return prepare(
        image,
        self.preproc,
        disable_preproc_contrast=disable_preproc_contrast,
        disable_preproc_grayscale=disable_preproc_grayscale,
        disable_preproc_static_crop=disable_preproc_static_crop,
    )