predictor.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 (
  22. SAMProcessor
  23. )
  24. from ..common import StaticInfer
  25. from ..base import BasicPredictor
  26. from .results import SAMSegResult
  27. class OVSegPredictor(BasicPredictor):
  28. entities = MODELS
  29. _FUNC_MAP = {}
  30. register = FuncRegister(_FUNC_MAP)
  31. def __init__(self, *args, **kwargs):
  32. """Initializes DetPredictor.
  33. Args:
  34. *args: Arbitrary positional arguments passed to the superclass.
  35. **kwargs: Arbitrary keyword arguments passed to the superclass.
  36. """
  37. super().__init__(*args, **kwargs)
  38. self.pre_ops, self.infer, self.processor = self._build()
  39. def _build_batch_sampler(self):
  40. return ImageBatchSampler()
  41. def _get_result_class(self):
  42. return SAMSegResult
  43. def _build(self):
  44. # build model preprocess ops
  45. pre_ops = [ReadImage(format="RGB")]
  46. for cfg in self.config.get("Preprocess", []):
  47. tf_key = cfg["type"]
  48. func = self._FUNC_MAP[tf_key]
  49. cfg.pop("type")
  50. args = cfg
  51. op = func(self, **args) if args else func(self)
  52. if op:
  53. pre_ops.append(op)
  54. # build infer
  55. infer = StaticInfer(
  56. model_dir=self.model_dir,
  57. model_prefix=self.MODEL_FILE_PREFIX,
  58. option=self.pp_option,
  59. )
  60. # build model specific processor, it's required for a OV model.
  61. processor_cfg = self.config["Processor"]
  62. tf_key = processor_cfg["type"]
  63. func = self._FUNC_MAP[tf_key]
  64. processor_cfg.pop("type")
  65. args = processor_cfg
  66. processor = func(self, **args) if args else func(self)
  67. return pre_ops, infer, processor
  68. def process(self, batch_data: List[Any], prompts: Dict[str, Any]):
  69. """
  70. Process a batch of data through the preprocessing, inference, and postprocessing.
  71. Args:
  72. batch_data (List[str]): A batch of input data (e.g., image file paths).
  73. prompt (Dict[str, Any]): Prompt for open vocabulary segmentation.
  74. Returns:
  75. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names
  76. for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  77. """
  78. image_paths = batch_data
  79. src_images = self.pre_ops[0](batch_data)
  80. datas = src_images
  81. # preprocess
  82. for pre_op in self.pre_ops[1:-1]:
  83. datas = pre_op(datas)
  84. # use Model-specific preprocessor to format batch inputs
  85. batch_inputs = self.processor.preprocess(datas, **prompts)
  86. # do infer
  87. batch_preds = self.infer(batch_inputs)
  88. # postprocess
  89. masks = self.processor.postprocess(batch_preds)
  90. return {
  91. "input_path": image_paths,
  92. "input_img": src_images,
  93. "prompts": [prompts] * len(image_paths),
  94. "masks": masks,
  95. }
  96. @register("SAMProcessor")
  97. def build_sam_preprocessor(self, size=1024, mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375]):
  98. return SAMProcessor(
  99. size=size,
  100. img_mean=mean,
  101. img_std=std
  102. )