predictor.py 3.9 KB

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