predictor.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 BasicPredictor
  24. from .results import SAMSegResult
  25. class OVSegPredictor(BasicPredictor):
  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 = StaticInfer(
  54. model_dir=self.model_dir,
  55. model_prefix=self.MODEL_FILE_PREFIX,
  56. option=self.pp_option,
  57. )
  58. # build model specific processor, it's required for a OV model.
  59. processor_cfg = self.config["Processor"]
  60. tf_key = processor_cfg["type"]
  61. func = self._FUNC_MAP[tf_key]
  62. processor_cfg.pop("type")
  63. args = processor_cfg
  64. processor = func(self, **args) if args else func(self)
  65. return pre_ops, infer, processor
  66. def process(self, batch_data: List[Any], prompts: Dict[str, Any]):
  67. """
  68. Process a batch of data through the preprocessing, inference, and postprocessing.
  69. Args:
  70. batch_data (List[str]): A batch of input data (e.g., image file paths).
  71. prompt (Dict[str, Any]): Prompt for open vocabulary segmentation.
  72. Returns:
  73. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names
  74. for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  75. """
  76. image_paths = batch_data
  77. src_images = self.pre_ops[0](batch_data)
  78. datas = src_images
  79. # preprocess
  80. for pre_op in self.pre_ops[1:-1]:
  81. datas = pre_op(datas)
  82. # use Model-specific preprocessor to format batch inputs
  83. batch_inputs = self.processor.preprocess(datas, **prompts)
  84. # do infer
  85. batch_preds = self.infer(batch_inputs)
  86. # postprocess
  87. masks = self.processor.postprocess(batch_preds)
  88. return {
  89. "input_path": image_paths,
  90. "input_img": src_images,
  91. "prompts": [prompts] * len(image_paths),
  92. "masks": masks,
  93. }
  94. @register("SAMProcessor")
  95. def build_sam_preprocessor(
  96. self, size=1024, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375]
  97. ):
  98. return SAMProcessor(size=size, img_mean=mean, img_std=std)