predictor.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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.general_recognition.model_list import MODELS
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ...common.reader import ReadImage
  20. from ..common import (
  21. Resize,
  22. ResizeByShort,
  23. Normalize,
  24. ToCHWImage,
  25. ToBatch,
  26. )
  27. from ..base import BasePredictor
  28. from .processors import NormalizeFeatures
  29. from .result import IdentityResult
  30. class ImageFeaturePredictor(BasePredictor):
  31. """ImageFeaturePredictor that inherits from BasePredictor."""
  32. entities = MODELS
  33. _FUNC_MAP = {}
  34. register = FuncRegister(_FUNC_MAP)
  35. def __init__(self, *args: List, **kwargs: Dict) -> None:
  36. """Initializes ClasPredictor.
  37. Args:
  38. *args: Arbitrary positional arguments passed to the superclass.
  39. **kwargs: Arbitrary keyword arguments passed to the superclass.
  40. """
  41. super().__init__(*args, **kwargs)
  42. self.preprocessors, self.infer, self.postprocessors = self._build()
  43. def _build_batch_sampler(self) -> ImageBatchSampler:
  44. """Builds and returns an ImageBatchSampler instance.
  45. Returns:
  46. ImageBatchSampler: An instance of ImageBatchSampler.
  47. """
  48. return ImageBatchSampler()
  49. def _get_result_class(self) -> type:
  50. """Returns the result class, IdentityResult.
  51. Returns:
  52. type: The IdentityResult class.
  53. """
  54. return IdentityResult
  55. def _build(self) -> Tuple:
  56. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  57. Returns:
  58. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  59. """
  60. preprocessors = {"Read": ReadImage(format="RGB")}
  61. for cfg in self.config["PreProcess"]["transform_ops"]:
  62. tf_key = list(cfg.keys())[0]
  63. func = self._FUNC_MAP[tf_key]
  64. args = cfg.get(tf_key, {})
  65. if args is not None and "return_numpy" in args:
  66. args.pop("return_numpy")
  67. name, op = func(self, **args) if args else func(self)
  68. preprocessors[name] = op
  69. preprocessors["ToBatch"] = ToBatch()
  70. infer = self.create_static_infer()
  71. postprocessors = {}
  72. for key in self.config["PostProcess"]:
  73. func = self._FUNC_MAP.get(key)
  74. args = self.config["PostProcess"].get(key, {})
  75. name, op = func(self, **args) if args else func(self)
  76. postprocessors[name] = op
  77. return preprocessors, infer, postprocessors
  78. def process(self, batch_data: List[Union[str, np.ndarray]]) -> Dict[str, Any]:
  79. """
  80. Process a batch of data through the preprocessing, inference, and postprocessing.
  81. Args:
  82. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  83. Returns:
  84. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  85. """
  86. batch_raw_imgs = self.preprocessors["Read"](imgs=batch_data.instances)
  87. batch_imgs = self.preprocessors["Resize"](imgs=batch_raw_imgs)
  88. batch_imgs = self.preprocessors["Normalize"](imgs=batch_imgs)
  89. batch_imgs = self.preprocessors["ToCHW"](imgs=batch_imgs)
  90. x = self.preprocessors["ToBatch"](imgs=batch_imgs)
  91. batch_preds = self.infer(x=x)
  92. features = self.postprocessors["NormalizeFeatures"](batch_preds)
  93. return {
  94. "input_path": batch_data.input_paths,
  95. "page_index": batch_data.page_indexes,
  96. "input_img": batch_raw_imgs,
  97. "feature": features,
  98. }
  99. @register("ResizeImage")
  100. # TODO(gaotingquan): backend & interpolation
  101. def build_resize(
  102. self, resize_short=None, size=None, backend="cv2", interpolation="LINEAR"
  103. ):
  104. assert resize_short or size
  105. if resize_short:
  106. op = ResizeByShort(
  107. target_short_edge=resize_short, size_divisor=None, interp="LINEAR"
  108. )
  109. else:
  110. op = Resize(target_size=size)
  111. return "Resize", op
  112. @register("NormalizeImage")
  113. def build_normalize(
  114. self,
  115. mean=[0.485, 0.456, 0.406],
  116. std=[0.229, 0.224, 0.225],
  117. scale=1 / 255,
  118. order="",
  119. channel_num=3,
  120. ):
  121. assert channel_num == 3
  122. return "Normalize", Normalize(scale=scale, mean=mean, std=std)
  123. @register("ToCHWImage")
  124. def build_to_chw(self):
  125. return "ToCHW", ToCHWImage()
  126. @register("NormalizeFeatures")
  127. def build_normalize_features(self):
  128. return "NormalizeFeatures", NormalizeFeatures()