predictor.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Any, Union, Dict, List, Tuple, Optional, Callable
  15. import numpy as np
  16. import inspect
  17. from ....utils.func_register import FuncRegister
  18. from ....modules.open_vocabulary_segmentation.model_list import MODELS
  19. from ...common.batch_sampler import ImageBatchSampler
  20. from ...common.reader import ReadImage
  21. from .processors import SAMProcessor
  22. from ..common import StaticInfer
  23. from ..base import BasePredictor
  24. from .results import SAMSegResult
  25. class OVSegPredictor(BasePredictor):
  26. entities = MODELS
  27. _FUNC_MAP = {}
  28. register = FuncRegister(_FUNC_MAP)
  29. def __init__(self, *args, **kwargs):
  30. """Initializes DetPredictor.
  31. Args:
  32. *args: Arbitrary positional arguments passed to the superclass.
  33. **kwargs: Arbitrary keyword arguments passed to the superclass.
  34. """
  35. super().__init__(*args, **kwargs)
  36. self.pre_ops, self.infer, self.processor = self._build()
  37. def _build_batch_sampler(self):
  38. return ImageBatchSampler()
  39. def _get_result_class(self):
  40. return SAMSegResult
  41. def _build(self):
  42. # build model preprocess ops
  43. pre_ops = [ReadImage(format="RGB")]
  44. for cfg in self.config.get("Preprocess", []):
  45. tf_key = cfg["type"]
  46. func = self._FUNC_MAP[tf_key]
  47. cfg.pop("type")
  48. args = cfg
  49. op = func(self, **args) if args else func(self)
  50. if op:
  51. pre_ops.append(op)
  52. # build infer
  53. infer = self.create_static_infer()
  54. # build model specific processor, it's required for a OV model.
  55. processor_cfg = self.config["Processor"]
  56. tf_key = processor_cfg["type"]
  57. func = self._FUNC_MAP[tf_key]
  58. processor_cfg.pop("type")
  59. args = processor_cfg
  60. processor = func(self, **args) if args else func(self)
  61. return pre_ops, infer, processor
  62. def process(self, batch_data: List[Any], prompts: Dict[str, Any]):
  63. """
  64. Process a batch of data through the preprocessing, inference, and postprocessing.
  65. Args:
  66. batch_data (List[str]): A batch of input data (e.g., image file paths).
  67. prompt (Dict[str, Any]): Prompt for open vocabulary segmentation.
  68. Returns:
  69. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names
  70. for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  71. """
  72. image_paths = batch_data.input_paths
  73. src_images = self.pre_ops[0](batch_data.instances)
  74. datas = src_images
  75. # preprocess
  76. for pre_op in self.pre_ops[1:-1]:
  77. datas = pre_op(datas)
  78. # use Model-specific preprocessor to format batch inputs
  79. batch_inputs = self.processor.preprocess(datas, **prompts)
  80. # do infer
  81. batch_preds = self.infer(batch_inputs)
  82. # postprocess
  83. masks = self.processor.postprocess(batch_preds)
  84. return {
  85. "input_path": image_paths,
  86. "input_img": src_images,
  87. "prompts": [prompts] * len(image_paths),
  88. "masks": masks,
  89. }
  90. @register("SAMProcessor")
  91. def build_sam_preprocessor(
  92. self, size=1024, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375]
  93. ):
  94. return SAMProcessor(size=size, img_mean=mean, img_std=std)