predictor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. img_size: Optional[Union[int, Tuple[int, int]]] = None,
  42. threshold: Optional[Union[float, dict]] = None,
  43. layout_nms: Optional[bool] = None,
  44. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  45. layout_merge_bboxes_mode: Optional[str] = None,
  46. **kwargs,
  47. ):
  48. """Initializes DetPredictor.
  49. Args:
  50. *args: Arbitrary positional arguments passed to the superclass.
  51. img_size (Optional[Union[int, Tuple[int, int]]], optional): The input image size (w, h). Defaults to None.
  52. threshold (Optional[float], optional): The threshold for filtering out low-confidence predictions.
  53. Defaults to None.
  54. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to False.
  55. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  56. Defaults to None.
  57. If it's a single number, then both width and height are used.
  58. If it's a tuple of two numbers, then they are used separately for width and height respectively.
  59. If it's None, then no unclipping will be performed.
  60. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  61. **kwargs: Arbitrary keyword arguments passed to the superclass.
  62. """
  63. super().__init__(*args, **kwargs)
  64. if img_size is not None:
  65. assert (
  66. self.model_name not in STATIC_SHAPE_MODEL_LIST
  67. ), f"The model {self.model_name} is not supported set input shape"
  68. if isinstance(img_size, int):
  69. img_size = (img_size, img_size)
  70. elif isinstance(img_size, (tuple, list)):
  71. assert len(img_size) == 2, f"The length of `img_size` should be 2."
  72. else:
  73. raise ValueError(
  74. f"The type of `img_size` must be int or Tuple[int, int], but got {type(img_size)}."
  75. )
  76. if layout_unclip_ratio is not None:
  77. if isinstance(layout_unclip_ratio, float):
  78. layout_unclip_ratio = (layout_unclip_ratio, layout_unclip_ratio)
  79. elif isinstance(layout_unclip_ratio, (tuple, list)):
  80. assert len(layout_unclip_ratio) == 2, f"The length of `layout_unclip_ratio` should be 2."
  81. else:
  82. raise ValueError(
  83. f"The type of `layout_unclip_ratio` must be float or Tuple[float, float], but got {type(layout_unclip_ratio)}."
  84. )
  85. if layout_merge_bboxes_mode is not None:
  86. assert layout_merge_bboxes_mode in ["union", "large", "small"], \
  87. f"The value of `layout_merge_bboxes_mode` must be one of ['union', 'large', 'small'], but got {layout_merge_bboxes_mode}"
  88. self.img_size = img_size
  89. self.threshold = threshold
  90. self.layout_nms = layout_nms
  91. self.layout_unclip_ratio = layout_unclip_ratio
  92. self.layout_merge_bboxes_mode = layout_merge_bboxes_mode
  93. self.pre_ops, self.infer, self.post_op = self._build()
  94. def _build_batch_sampler(self):
  95. return ImageBatchSampler()
  96. def _get_result_class(self):
  97. return DetResult
  98. def _build(self) -> Tuple:
  99. """Build the preprocessors, inference engine, and postprocessors based on the configuration.
  100. Returns:
  101. tuple: A tuple containing the preprocessors, inference engine, and postprocessors.
  102. """
  103. # build preprocess ops
  104. pre_ops = [ReadImage(format="RGB")]
  105. for cfg in self.config["Preprocess"]:
  106. tf_key = cfg["type"]
  107. func = self._FUNC_MAP[tf_key]
  108. cfg.pop("type")
  109. args = cfg
  110. op = func(self, **args) if args else func(self)
  111. if op:
  112. pre_ops.append(op)
  113. pre_ops.append(self.build_to_batch())
  114. if self.img_size is not None:
  115. if isinstance(pre_ops[1], Resize):
  116. pre_ops.pop(1)
  117. pre_ops.insert(1, self.build_resize(self.img_size, False, 2))
  118. # build infer
  119. infer = StaticInfer(
  120. model_dir=self.model_dir,
  121. model_prefix=self.MODEL_FILE_PREFIX,
  122. option=self.pp_option,
  123. )
  124. # build postprocess op
  125. post_op = self.build_postprocess()
  126. return pre_ops, infer, post_op
  127. def _format_output(self, pred: Sequence[Any]) -> List[dict]:
  128. """
  129. Transform batch outputs into a list of single image output.
  130. Args:
  131. pred (Sequence[Any]): The input predictions, which can be either a list of 3 or 4 elements.
  132. - When len(pred) == 4, it is expected to be in the format [boxes, class_ids, scores, masks],
  133. compatible with SOLOv2 output.
  134. - When len(pred) == 3, it is expected to be in the format [boxes, box_nums, masks],
  135. compatible with Instance Segmentation output.
  136. Returns:
  137. List[dict]: A list of dictionaries, each containing either 'class_id' and 'masks' (for SOLOv2),
  138. or 'boxes' and 'masks' (for Instance Segmentation), or just 'boxes' if no masks are provided.
  139. """
  140. box_idx_start = 0
  141. pred_box = []
  142. if len(pred) == 4:
  143. # Adapt to SOLOv2
  144. pred_class_id = []
  145. pred_mask = []
  146. pred_class_id.append([pred[1], pred[2]])
  147. pred_mask.append(pred[3])
  148. return [
  149. {
  150. "class_id": np.array(pred_class_id[i]),
  151. "masks": np.array(pred_mask[i]),
  152. }
  153. for i in range(len(pred_class_id))
  154. ]
  155. if len(pred) == 3:
  156. # Adapt to Instance Segmentation
  157. pred_mask = []
  158. for idx in range(len(pred[1])):
  159. np_boxes_num = pred[1][idx]
  160. box_idx_end = box_idx_start + np_boxes_num
  161. np_boxes = pred[0][box_idx_start:box_idx_end]
  162. pred_box.append(np_boxes)
  163. if len(pred) == 3:
  164. np_masks = pred[2][box_idx_start:box_idx_end]
  165. pred_mask.append(np_masks)
  166. box_idx_start = box_idx_end
  167. if len(pred) == 3:
  168. return [
  169. {"boxes": np.array(pred_box[i]), "masks": np.array(pred_mask[i])}
  170. for i in range(len(pred_box))
  171. ]
  172. else:
  173. return [{"boxes": np.array(res)} for res in pred_box]
  174. def process(self,
  175. batch_data: List[Any],
  176. threshold: Optional[Union[float, dict]] = None,
  177. layout_nms: Optional[bool] = None,
  178. layout_unclip_ratio: Optional[Union[float, Tuple[float, float]]] = None,
  179. layout_merge_bboxes_mode: Optional[str] = None,
  180. ):
  181. """
  182. Process a batch of data through the preprocessing, inference, and postprocessing.
  183. Args:
  184. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., image file paths).
  185. threshold (Optional[float, dict], optional): The threshold for filtering out low-confidence predictions.
  186. layout_nms (bool, optional): Whether to use layout-aware NMS. Defaults to None.
  187. layout_unclip_ratio (Optional[Union[float, Tuple[float, float]]], optional): The ratio of unclipping the bounding box.
  188. layout_merge_bboxes_mode (Optional[str], optional): The mode for merging bounding boxes. Defaults to None.
  189. Returns:
  190. dict: A dictionary containing the input path, raw image, class IDs, scores, and label names
  191. for every instance of the batch. Keys include 'input_path', 'input_img', 'class_ids', 'scores', and 'label_names'.
  192. """
  193. datas = batch_data
  194. # preprocess
  195. for pre_op in self.pre_ops[:-1]:
  196. datas = pre_op(datas)
  197. # use `ToBatch` format batch inputs
  198. batch_inputs = self.pre_ops[-1](datas)
  199. # do infer
  200. batch_preds = self.infer(batch_inputs)
  201. # process a batch of predictions into a list of single image result
  202. preds_list = self._format_output(batch_preds)
  203. # postprocess
  204. boxes = self.post_op(
  205. preds_list,
  206. datas,
  207. threshold = threshold or self.threshold,
  208. layout_nms=layout_nms or self.layout_nms,
  209. layout_unclip_ratio=layout_unclip_ratio or self.layout_unclip_ratio,
  210. layout_merge_bboxes_mode=layout_merge_bboxes_mode or self.layout_merge_bboxes_mode
  211. )
  212. return {
  213. "input_path": [data.get("img_path", None) for data in datas],
  214. "input_img": [data["ori_img"] for data in datas],
  215. "boxes": boxes,
  216. }
  217. @register("Resize")
  218. def build_resize(self, target_size, keep_ratio=False, interp=2):
  219. assert target_size
  220. if isinstance(interp, int):
  221. interp = {
  222. 0: "NEAREST",
  223. 1: "LINEAR",
  224. 2: "BICUBIC",
  225. 3: "AREA",
  226. 4: "LANCZOS4",
  227. }[interp]
  228. op = Resize(target_size=target_size[::-1], keep_ratio=keep_ratio, interp=interp)
  229. return op
  230. @register("NormalizeImage")
  231. def build_normalize(
  232. self,
  233. norm_type=None,
  234. mean=[0.485, 0.456, 0.406],
  235. std=[0.229, 0.224, 0.225],
  236. is_scale=True,
  237. ):
  238. if is_scale:
  239. scale = 1.0 / 255.0
  240. else:
  241. scale = 1
  242. if not norm_type or norm_type == "none":
  243. norm_type = "mean_std"
  244. if norm_type != "mean_std":
  245. mean = 0
  246. std = 1
  247. return Normalize(scale=scale, mean=mean, std=std)
  248. @register("Permute")
  249. def build_to_chw(self):
  250. return ToCHWImage()
  251. @register("Pad")
  252. def build_pad(self, fill_value=None, size=None):
  253. if fill_value is None:
  254. fill_value = [127.5, 127.5, 127.5]
  255. if size is None:
  256. size = [3, 640, 640]
  257. return DetPad(size=size, fill_value=fill_value)
  258. @register("PadStride")
  259. def build_pad_stride(self, stride=32):
  260. return PadStride(stride=stride)
  261. @register("WarpAffine")
  262. def build_warp_affine(self, input_h=512, input_w=512, keep_res=True):
  263. return WarpAffine(input_h=input_h, input_w=input_w, keep_res=keep_res)
  264. def build_to_batch(self):
  265. models_required_imgsize = [
  266. "DETR",
  267. "DINO",
  268. "RCNN",
  269. "YOLOv3",
  270. "CenterNet",
  271. "BlazeFace",
  272. "BlazeFace-FPN-SSH",
  273. "PP-DocLayout-L",
  274. ]
  275. if any(name in self.model_name for name in models_required_imgsize):
  276. ordered_required_keys = (
  277. "img_size",
  278. "img",
  279. "scale_factors",
  280. )
  281. else:
  282. ordered_required_keys = ("img", "scale_factors")
  283. return ToBatch(ordered_required_keys=ordered_required_keys)
  284. def build_postprocess(self):
  285. if self.threshold is None:
  286. self.threshold = self.config.get("draw_threshold", 0.5)
  287. if not self.layout_nms:
  288. self.layout_nms = self.config.get("layout_nms", None)
  289. if self.layout_unclip_ratio is None:
  290. self.layout_unclip_ratio = self.config.get("layout_unclip_ratio", None)
  291. if self.layout_merge_bboxes_mode is None:
  292. self.layout_merge_bboxes_mode = self.config.get("layout_merge_bboxes_mode", None)
  293. return DetPostProcess(
  294. labels=self.config["label_list"]
  295. )