predictor.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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, List, Sequence, Optional, Union, Tuple
  15. import numpy as np
  16. from ....utils.func_register import FuncRegister
  17. from ....modules.object_detection.model_list import MODELS
  18. from ...common.batch_sampler import ImageBatchSampler
  19. from ..common import StaticInfer
  20. from ..base import BasicPredictor
  21. from .processors import (
  22. DetPad,
  23. DetPostProcess,
  24. Normalize,
  25. PadStride,
  26. ReadImage,
  27. Resize,
  28. ToBatch,
  29. ToCHWImage,
  30. WarpAffine,
  31. )
  32. from .result import DetResult
  33. from .utils import STATIC_SHAPE_MODEL_LIST
  34. class DetPredictor(BasicPredictor):
  35. entities = MODELS
  36. _FUNC_MAP = {}
  37. register = FuncRegister(_FUNC_MAP)
  38. def __init__(
  39. self,
  40. *args,
  41. imgsz: Optional[Union[int, Tuple[int, int]]] = None,
  42. threshold: Optional[float] = None,
  43. **kwargs,
  44. ):
  45. """Initializes DetPredictor.
  46. Args:
  47. *args: Arbitrary positional arguments passed to the superclass.
  48. imgsz (Optional[Union[int, Tuple[int, int]]], optional): The input image size (w, h). Defaults to None.
  49. threshold (Optional[float], optional): The threshold for filtering out low-confidence predictions.
  50. Defaults to None.
  51. **kwargs: Arbitrary keyword arguments passed to the superclass.
  52. """
  53. super().__init__(*args, **kwargs)
  54. if imgsz is not None:
  55. assert (
  56. self.model_name not in STATIC_SHAPE_MODEL_LIST
  57. ), f"The model {self.model_name} is not supported set input shape"
  58. if isinstance(imgsz, int):
  59. imgsz = (imgsz, imgsz)
  60. elif isinstance(imgsz, (tuple, list)):
  61. assert len(imgsz) == 2, f"The length of `imgsz` should be 2."
  62. else:
  63. raise ValueError(
  64. f"The type of `imgsz` must be int or Tuple[int, int], but got {type(imgsz)}."
  65. )
  66. self.imgsz = imgsz
  67. self.threshold = threshold
  68. self.pre_ops, self.infer, self.post_op = self._build()
  69. def _build_batch_sampler(self):
  70. return ImageBatchSampler()
  71. def _get_result_class(self):
  72. return DetResult
  73. def _build(self) -> Tuple:
  74. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  75. Returns:
  76. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  77. """
  78. # build preprocess ops
  79. pre_ops = [ReadImage(format="RGB")]
  80. for cfg in self.config["Preprocess"]:
  81. tf_key = cfg["type"]
  82. func = self._FUNC_MAP[tf_key]
  83. cfg.pop("type")
  84. args = cfg
  85. op = func(self, **args) if args else func(self)
  86. if op:
  87. pre_ops.append(op)
  88. pre_ops.append(self.build_to_batch())
  89. if self.imgsz is not None:
  90. if isinstance(pre_ops[1], Resize):
  91. pre_ops.pop(1)
  92. pre_ops.insert(1, self.build_resize(self.imgsz, False, 2))
  93. # build infer
  94. infer = StaticInfer(
  95. model_dir=self.model_dir,
  96. model_prefix=self.MODEL_FILE_PREFIX,
  97. option=self.pp_option,
  98. )
  99. # build postprocess op
  100. post_op = self.build_postprocess()
  101. return pre_ops, infer, post_op
  102. def _format_output(self, pred: Sequence[Any]) -> List[dict]:
  103. """
  104. Transform batch outputs into a list of single image output.
  105. Args:
  106. pred (Sequence[Any]): The input predictions, which can be either a list of 3 or 4 elements.
  107. - When len(pred) == 4, it is expected to be in the format [boxes, class_ids, scores, masks],
  108. compatible with SOLOv2 output.
  109. - When len(pred) == 3, it is expected to be in the format [boxes, box_nums, masks],
  110. compatible with Instance Segmentation output.
  111. Returns:
  112. List[dict]: A list of dictionaries, each containing either 'class_id' and 'masks' (for SOLOv2),
  113. or 'boxes' and 'masks' (for Instance Segmentation), or just 'boxes' if no masks are provided.
  114. """
  115. box_idx_start = 0
  116. pred_box = []
  117. if len(pred) == 4:
  118. # Adapt to SOLOv2
  119. pred_class_id = []
  120. pred_mask = []
  121. pred_class_id.append([pred[1], pred[2]])
  122. pred_mask.append(pred[3])
  123. return [
  124. {
  125. "class_id": np.array(pred_class_id[i]),
  126. "masks": np.array(pred_mask[i]),
  127. }
  128. for i in range(len(pred_class_id))
  129. ]
  130. if len(pred) == 3:
  131. # Adapt to Instance Segmentation
  132. pred_mask = []
  133. for idx in range(len(pred[1])):
  134. np_boxes_num = pred[1][idx]
  135. box_idx_end = box_idx_start + np_boxes_num
  136. np_boxes = pred[0][box_idx_start:box_idx_end]
  137. pred_box.append(np_boxes)
  138. if len(pred) == 3:
  139. np_masks = pred[2][box_idx_start:box_idx_end]
  140. pred_mask.append(np_masks)
  141. box_idx_start = box_idx_end
  142. if len(pred) == 3:
  143. return [
  144. {"boxes": np.array(pred_box[i]), "masks": np.array(pred_mask[i])}
  145. for i in range(len(pred_box))
  146. ]
  147. else:
  148. return [{"boxes": np.array(res)} for res in pred_box]
  149. def process(self, batch_data: List[Any], threshold: Optional[float] = None):
  150. """
  151. Process a batch of data through the preprocessing, inference, and postprocessing.
  152. Args:
  153. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  154. Returns:
  155. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names
  156. for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  157. """
  158. datas = batch_data
  159. # preprocess
  160. for pre_op in self.pre_ops[:-1]:
  161. datas = pre_op(datas)
  162. # use `ToBatch` format batch inputs
  163. batch_inputs = self.pre_ops[-1](datas)
  164. # do infer
  165. batch_preds = self.infer(batch_inputs)
  166. # process a batch of predictions into a list of single image result
  167. preds_list = self._format_output(batch_preds)
  168. # postprocess
  169. boxes = self.post_op(
  170. preds_list, datas, threshold if threshold is not None else self.threshold
  171. )
  172. return {
  173. "input_path": [data.get("img_path", None) for data in datas],
  174. "input_img": [data["ori_img"] for data in datas],
  175. "boxes": boxes,
  176. }
  177. @register("Resize")
  178. def build_resize(self, target_size, keep_ratio=False, interp=2):
  179. assert target_size
  180. if isinstance(interp, int):
  181. interp = {
  182. 0: "NEAREST",
  183. 1: "LINEAR",
  184. 2: "BICUBIC",
  185. 3: "AREA",
  186. 4: "LANCZOS4",
  187. }[interp]
  188. op = Resize(target_size=target_size[::-1], keep_ratio=keep_ratio, interp=interp)
  189. return op
  190. @register("NormalizeImage")
  191. def build_normalize(
  192. self,
  193. norm_type=None,
  194. mean=[0.485, 0.456, 0.406],
  195. std=[0.229, 0.224, 0.225],
  196. is_scale=True,
  197. ):
  198. if is_scale:
  199. scale = 1.0 / 255.0
  200. else:
  201. scale = 1
  202. if not norm_type or norm_type == "none":
  203. norm_type = "mean_std"
  204. if norm_type != "mean_std":
  205. mean = 0
  206. std = 1
  207. return Normalize(scale=scale, mean=mean, std=std)
  208. @register("Permute")
  209. def build_to_chw(self):
  210. return ToCHWImage()
  211. @register("Pad")
  212. def build_pad(self, fill_value=None, size=None):
  213. if fill_value is None:
  214. fill_value = [127.5, 127.5, 127.5]
  215. if size is None:
  216. size = [3, 640, 640]
  217. return DetPad(size=size, fill_value=fill_value)
  218. @register("PadStride")
  219. def build_pad_stride(self, stride=32):
  220. return PadStride(stride=stride)
  221. @register("WarpAffine")
  222. def build_warp_affine(self, input_h=512, input_w=512, keep_res=True):
  223. return WarpAffine(input_h=input_h, input_w=input_w, keep_res=keep_res)
  224. def build_to_batch(self):
  225. models_required_imgsize = [
  226. "DETR",
  227. "DINO",
  228. "RCNN",
  229. "YOLOv3",
  230. "CenterNet",
  231. "BlazeFace",
  232. "BlazeFace-FPN-SSH",
  233. ]
  234. if any(name in self.model_name for name in models_required_imgsize):
  235. ordered_required_keys = (
  236. "img_size",
  237. "img",
  238. "scale_factors",
  239. )
  240. else:
  241. ordered_required_keys = ("img", "scale_factors")
  242. return ToBatch(ordered_required_keys=ordered_required_keys)
  243. def build_postprocess(self):
  244. return DetPostProcess(
  245. threshold=self.config["draw_threshold"],
  246. labels=self.config["label_list"],
  247. layout_postprocess=self.config.get("layout_postprocess", False),
  248. )