predictor.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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
  15. import numpy as np
  16. from ....utils.func_register import FuncRegister
  17. from ....modules.semantic_segmentation.model_list import MODELS
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...common.reader import ReadImage
  20. from ..common import (
  21. ResizeByShort,
  22. Normalize,
  23. ToCHWImage,
  24. ToBatch,
  25. )
  26. from .processors import Resize, SegPostProcess
  27. from ..base import BasePredictor
  28. from .result import SegResult
  29. class SegPredictor(BasePredictor):
  30. """SegPredictor that inherits from BasePredictor."""
  31. entities = MODELS
  32. _FUNC_MAP = {}
  33. register = FuncRegister(_FUNC_MAP)
  34. def __init__(
  35. self,
  36. target_size: Union[int, Tuple[int], None] = None,
  37. *args: List,
  38. **kwargs: Dict,
  39. ) -> None:
  40. """Initializes SegPredictor.
  41. Args:
  42. target_size: Image size used for inference.
  43. *args: Arbitrary positional arguments passed to the superclass.
  44. **kwargs: Arbitrary keyword arguments passed to the superclass.
  45. """
  46. super().__init__(*args, **kwargs)
  47. self.target_size = target_size
  48. self.preprocessors, self.infer, self.postprocessers = self._build()
  49. def _build_batch_sampler(self) -> ImageBatchSampler:
  50. """Builds and returns an ImageBatchSampler instance.
  51. Returns:
  52. ImageBatchSampler: An instance of ImageBatchSampler.
  53. """
  54. return ImageBatchSampler()
  55. def _get_result_class(self) -> type:
  56. """Returns the result class, SegResult.
  57. Returns:
  58. type: The SegResult class.
  59. """
  60. return SegResult
  61. def _build(self) -> Tuple:
  62. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  63. Returns:
  64. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  65. """
  66. preprocessors = {"Read": ReadImage(format="RGB")}
  67. preprocessors["ToCHW"] = ToCHWImage()
  68. for cfg in self.config["Deploy"]["transforms"]:
  69. tf_key = cfg.pop("type")
  70. func = self._FUNC_MAP[tf_key]
  71. args = cfg
  72. name, op = func(self, **args) if args else func(self)
  73. preprocessors[name] = op
  74. preprocessors["ToBatch"] = ToBatch()
  75. if "Resize" not in preprocessors:
  76. _, op = self._FUNC_MAP["Resize"](self, target_size=-1)
  77. preprocessors["Resize"] = op
  78. if self.target_size is not None:
  79. _, op = self._FUNC_MAP["Resize"](self, target_size=self.target_size)
  80. preprocessors["Resize"] = op
  81. infer = self.create_static_infer()
  82. postprocessers = SegPostProcess()
  83. return preprocessors, infer, postprocessers
  84. def process(
  85. self,
  86. batch_data: List[Union[str, np.ndarray]],
  87. target_size: Union[int, Tuple[int], None] = None,
  88. ) -> Dict[str, Any]:
  89. """
  90. Process a batch of data through the preprocessing, inference, and postprocessing.
  91. Args:
  92. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  93. target_size: Image size used for inference.
  94. Returns:
  95. dict: A dictionary containing the input path, raw image, and predicted segmentation maps for every instance of the batch. Keys include 'input_path', 'input_img', and 'pred'.
  96. """
  97. batch_raw_imgs = self.preprocessors["Read"](imgs=batch_data.instances)
  98. batch_imgs = self.preprocessors["Resize"](
  99. imgs=batch_raw_imgs, target_size=target_size
  100. )
  101. batch_imgs = self.preprocessors["Normalize"](imgs=batch_imgs)
  102. batch_imgs = self.preprocessors["ToCHW"](imgs=batch_imgs)
  103. x = self.preprocessors["ToBatch"](imgs=batch_imgs)
  104. batch_preds = self.infer(x=x)
  105. if len(batch_data) > 1:
  106. batch_preds = np.split(batch_preds[0], len(batch_data), axis=0)
  107. # postprocess
  108. batch_preds = self.postprocessers(batch_preds, batch_raw_imgs)
  109. return {
  110. "input_path": batch_data.input_paths,
  111. "page_index": batch_data.page_indexes,
  112. "input_img": batch_raw_imgs,
  113. "pred": batch_preds,
  114. }
  115. @register("Normalize")
  116. def build_normalize(
  117. self,
  118. mean=0.5,
  119. std=0.5,
  120. ):
  121. op = Normalize(mean=mean, std=std)
  122. return "Normalize", op
  123. @register("Resize")
  124. def build_resize(
  125. self,
  126. target_size=-1,
  127. keep_ratio=True,
  128. size_divisor=32,
  129. interp="LINEAR",
  130. ):
  131. op = Resize(
  132. target_size=target_size,
  133. keep_ratio=keep_ratio,
  134. size_divisor=size_divisor,
  135. interp=interp,
  136. )
  137. return "Resize", op