predictor.py 13 KB

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