predictor.py 6.1 KB

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