predictor.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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.image_classification.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 Crop, Topk
  29. from .result import TopkResult
  30. class ClasPredictor(BasePredictor):
  31. """ClasPredictor that inherits from BasePredictor."""
  32. entities = MODELS
  33. _FUNC_MAP = {}
  34. register = FuncRegister(_FUNC_MAP)
  35. def __init__(
  36. self, topk: Union[int, None] = None, *args: List, **kwargs: Dict
  37. ) -> None:
  38. """Initializes ClasPredictor.
  39. Args:
  40. topk (int, optional): The number of top-k predictions to return. If None, it will be depending on config of inference or predict. Defaults to None.
  41. *args: Arbitrary positional arguments passed to the superclass.
  42. **kwargs: Arbitrary keyword arguments passed to the superclass.
  43. """
  44. super().__init__(*args, **kwargs)
  45. self.topk = topk
  46. self.preprocessors, self.infer, self.postprocessors = self._build()
  47. def _build_batch_sampler(self) -> ImageBatchSampler:
  48. """Builds and returns an ImageBatchSampler instance.
  49. Returns:
  50. ImageBatchSampler: An instance of ImageBatchSampler.
  51. """
  52. return ImageBatchSampler()
  53. def _get_result_class(self) -> type:
  54. """Returns the result class, TopkResult.
  55. Returns:
  56. type: The TopkResult class.
  57. """
  58. return TopkResult
  59. def _build(self) -> Tuple:
  60. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  61. Returns:
  62. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  63. """
  64. preprocessors = {"Read": ReadImage(format="RGB")}
  65. for cfg in self.config["PreProcess"]["transform_ops"]:
  66. tf_key = list(cfg.keys())[0]
  67. func = self._FUNC_MAP[tf_key]
  68. args = cfg.get(tf_key, {})
  69. name, op = func(self, **args) if args else func(self)
  70. preprocessors[name] = op
  71. preprocessors["ToBatch"] = ToBatch()
  72. infer = self.create_static_infer()
  73. postprocessors = {}
  74. for key in self.config["PostProcess"]:
  75. func = self._FUNC_MAP.get(key)
  76. args = self.config["PostProcess"].get(key, {})
  77. name, op = func(self, **args) if args else func(self)
  78. postprocessors[name] = op
  79. return preprocessors, infer, postprocessors
  80. def process(
  81. self, batch_data: List[Union[str, np.ndarray]], topk: Union[int, None] = None
  82. ) -> Dict[str, Any]:
  83. """
  84. Process a batch of data through the preprocessing, inference, and postprocessing.
  85. Args:
  86. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  87. topk: The number of top predictions to keep. If None, it will be depending on `self.topk`. Defaults to None.
  88. Returns:
  89. 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'.
  90. """
  91. batch_raw_imgs = self.preprocessors["Read"](imgs=batch_data.instances)
  92. batch_imgs = self.preprocessors["Resize"](imgs=batch_raw_imgs)
  93. if "Crop" in self.preprocessors:
  94. batch_imgs = self.preprocessors["Crop"](imgs=batch_imgs)
  95. batch_imgs = self.preprocessors["Normalize"](imgs=batch_imgs)
  96. batch_imgs = self.preprocessors["ToCHW"](imgs=batch_imgs)
  97. x = self.preprocessors["ToBatch"](imgs=batch_imgs)
  98. batch_preds = self.infer(x=x)
  99. batch_class_ids, batch_scores, batch_label_names = self.postprocessors["Topk"](
  100. batch_preds, topk=topk or self.topk
  101. )
  102. return {
  103. "input_path": batch_data.input_paths,
  104. "page_index": batch_data.page_indexes,
  105. "input_img": batch_raw_imgs,
  106. "class_ids": batch_class_ids,
  107. "scores": batch_scores,
  108. "label_names": batch_label_names,
  109. }
  110. @register("ResizeImage")
  111. # TODO(gaotingquan): backend & interpolation
  112. def build_resize(
  113. self, resize_short=None, size=None, backend="cv2", interpolation="LINEAR"
  114. ):
  115. assert resize_short or size
  116. if resize_short:
  117. op = ResizeByShort(
  118. target_short_edge=resize_short,
  119. size_divisor=None,
  120. interp=interpolation,
  121. backend=backend,
  122. )
  123. else:
  124. op = Resize(
  125. target_size=size,
  126. size_divisor=None,
  127. interp=interpolation,
  128. backend=backend,
  129. )
  130. return "Resize", op
  131. @register("CropImage")
  132. def build_crop(self, size=224):
  133. return "Crop", Crop(crop_size=size)
  134. @register("NormalizeImage")
  135. def build_normalize(
  136. self,
  137. mean=[0.485, 0.456, 0.406],
  138. std=[0.229, 0.224, 0.225],
  139. scale=1 / 255,
  140. order="",
  141. channel_num=3,
  142. ):
  143. assert channel_num == 3
  144. assert order == ""
  145. return "Normalize", Normalize(scale=scale, mean=mean, std=std)
  146. @register("ToCHWImage")
  147. def build_to_chw(self):
  148. return "ToCHW", ToCHWImage()
  149. @register("Topk")
  150. def build_topk(self, topk, label_list=None):
  151. if not self.topk:
  152. self.topk = int(topk)
  153. return "Topk", Topk(class_ids=label_list)