predictor.py 13 KB

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