predictor.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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. import shutil
  15. import tempfile
  16. from typing import Any, Dict, Iterator, List, Tuple
  17. from ....modules.m_3d_bev_detection.model_list import MODELS
  18. from ....utils import logging
  19. from ....utils.deps import function_requires_deps
  20. from ....utils.func_register import FuncRegister
  21. from ...common.batch_sampler import Det3DBatchSampler
  22. from ...common.reader import ReadNuscenesData
  23. from ..base import BasePredictor
  24. from ..base.predictor.base_predictor import PredictionWrap
  25. from .processors import (
  26. GetInferInput,
  27. LoadMultiViewImageFromFiles,
  28. LoadPointsFromFile,
  29. LoadPointsFromMultiSweeps,
  30. NormalizeImage,
  31. PadImage,
  32. ResizeImage,
  33. SampleFilterByKey,
  34. )
  35. from .result import BEV3DDetResult
  36. class BEVDet3DPredictor(BasePredictor):
  37. """BEVDet3DPredictor that inherits from BasePredictor."""
  38. entities = MODELS
  39. _FUNC_MAP = {}
  40. register = FuncRegister(_FUNC_MAP)
  41. def __init__(self, *args: List, **kwargs: Dict) -> None:
  42. """Initializes BEVDet3DPredictor.
  43. Args:
  44. *args: Arbitrary positional arguments passed to the superclass.
  45. **kwargs: Arbitrary keyword arguments passed to the superclass.
  46. """
  47. self.temp_dir = tempfile.mkdtemp()
  48. logging.info(
  49. f"infer data will be stored in temporary directory {self.temp_dir}"
  50. )
  51. super().__init__(*args, **kwargs)
  52. self.pre_tfs, self.infer = self._build()
  53. def _build_batch_sampler(self) -> Det3DBatchSampler:
  54. """Builds and returns an Det3DBatchSampler instance.
  55. Returns:
  56. Det3DBatchSampler: An instance of Det3DBatchSampler.
  57. """
  58. return Det3DBatchSampler(temp_dir=self.temp_dir)
  59. def _get_result_class(self) -> type:
  60. """Returns the result class, BEV3DDetResult.
  61. Returns:
  62. type: The BEV3DDetResult class.
  63. """
  64. return BEV3DDetResult
  65. @function_requires_deps("paddlepaddle")
  66. def _build(self) -> Tuple:
  67. """Build the preprocessors and inference engine based on the configuration.
  68. Returns:
  69. tuple: A tuple containing the preprocessors and inference engine.
  70. """
  71. import paddle
  72. if paddle.is_compiled_with_cuda() and not paddle.is_compiled_with_rocm():
  73. from ....ops.iou3d_nms import nms_gpu # noqa: F401
  74. from ....ops.voxelize import hard_voxelize # noqa: F401
  75. else:
  76. logging.error("3D BEVFusion custom ops only support GPU platform!")
  77. pre_tfs = {"Read": ReadNuscenesData()}
  78. for cfg in self.config["PreProcess"]["transform_ops"]:
  79. tf_key = list(cfg.keys())[0]
  80. func = self._FUNC_MAP[tf_key]
  81. args = cfg.get(tf_key, {})
  82. name, op = func(self, **args) if args else func(self)
  83. if op:
  84. pre_tfs[name] = op
  85. pre_tfs["GetInferInput"] = GetInferInput()
  86. infer = self.create_static_infer()
  87. return pre_tfs, infer
  88. def _format_output(
  89. self, infer_input: List[Any], outs: List[Any], img_metas: Dict[str, Any]
  90. ) -> Dict[str, Any]:
  91. """format inference input and output into predict result
  92. Args:
  93. infer_input(List): Model infer inputs with list containing images, points and lidar2img matrix.
  94. outs(List): Model infer output containing bboxes, scores, labels result.
  95. img_metas(Dict): Image metas info of input sample.
  96. Returns:
  97. Dict: A Dict containing formatted inference output results.
  98. """
  99. input_lidar_path = img_metas["input_lidar_path"]
  100. input_img_paths = img_metas["input_img_paths"]
  101. sample_id = img_metas["sample_id"]
  102. results = {}
  103. out_bboxes_3d = []
  104. out_scores_3d = []
  105. out_labels_3d = []
  106. input_imgs = []
  107. input_points = []
  108. input_lidar2imgs = []
  109. input_ids = []
  110. input_lidar_path_list = []
  111. input_img_paths_list = []
  112. out_bboxes_3d.append(outs[0])
  113. out_labels_3d.append(outs[1])
  114. out_scores_3d.append(outs[2])
  115. input_imgs.append(infer_input[1])
  116. input_points.append(infer_input[0])
  117. input_lidar2imgs.append(infer_input[2])
  118. input_ids.append(sample_id)
  119. input_lidar_path_list.append(input_lidar_path)
  120. input_img_paths_list.append(input_img_paths)
  121. results["input_path"] = input_lidar_path_list
  122. results["input_img_paths"] = input_img_paths_list
  123. results["sample_id"] = input_ids
  124. results["boxes_3d"] = out_bboxes_3d
  125. results["labels_3d"] = out_labels_3d
  126. results["scores_3d"] = out_scores_3d
  127. return results
  128. def process(self, batch_data: List[str]) -> Dict[str, Any]:
  129. """
  130. Process a batch of data through the preprocessing and inference.
  131. Args:
  132. batch_data (List[str]): A batch of input data (e.g., sample anno file paths).
  133. Returns:
  134. dict: A dictionary containing the input path, input img, input points, input lidar2img, output bboxes, output labels, output scores and label names. Keys include 'input_path', 'input_img', 'input_points', 'input_lidar2img', 'boxes_3d', 'labels_3d' and 'scores_3d'.
  135. """
  136. sample = self.pre_tfs["Read"](batch_data=batch_data)
  137. sample = self.pre_tfs["LoadPointsFromFile"](results=sample[0])
  138. sample = self.pre_tfs["LoadPointsFromMultiSweeps"](results=sample)
  139. sample = self.pre_tfs["LoadMultiViewImageFromFiles"](sample=sample)
  140. sample = self.pre_tfs["ResizeImage"](results=sample)
  141. sample = self.pre_tfs["NormalizeImage"](results=sample)
  142. sample = self.pre_tfs["PadImage"](results=sample)
  143. sample = self.pre_tfs["SampleFilterByKey"](sample=sample)
  144. infer_input, img_metas = self.pre_tfs["GetInferInput"](sample=sample)
  145. infer_output = self.infer(x=infer_input)
  146. results = self._format_output(infer_input, infer_output, img_metas)
  147. return results
  148. @register("LoadPointsFromFile")
  149. def build_load_img_from_file(
  150. self, load_dim=6, use_dim=[0, 1, 2], shift_height=False, use_color=False
  151. ):
  152. return "LoadPointsFromFile", LoadPointsFromFile(
  153. load_dim=load_dim,
  154. use_dim=use_dim,
  155. shift_height=shift_height,
  156. use_color=use_color,
  157. )
  158. @register("LoadPointsFromMultiSweeps")
  159. def build_load_points_from_multi_sweeps(
  160. self,
  161. sweeps_num=10,
  162. load_dim=5,
  163. use_dim=[0, 1, 2, 4],
  164. pad_empty_sweeps=False,
  165. remove_close=False,
  166. test_mode=False,
  167. point_cloud_angle_range=None,
  168. ):
  169. return "LoadPointsFromMultiSweeps", LoadPointsFromMultiSweeps(
  170. sweeps_num=sweeps_num,
  171. load_dim=load_dim,
  172. use_dim=use_dim,
  173. pad_empty_sweeps=pad_empty_sweeps,
  174. remove_close=remove_close,
  175. test_mode=test_mode,
  176. point_cloud_angle_range=point_cloud_angle_range,
  177. )
  178. @register("LoadMultiViewImageFromFiles")
  179. def build_load_multi_view_image_from_files(
  180. self,
  181. to_float32=False,
  182. project_pts_to_img_depth=False,
  183. cam_depth_range=[4.0, 45.0, 1.0],
  184. constant_std=0.5,
  185. imread_flag=-1,
  186. ):
  187. return "LoadMultiViewImageFromFiles", LoadMultiViewImageFromFiles(
  188. to_float32=to_float32,
  189. project_pts_to_img_depth=project_pts_to_img_depth,
  190. cam_depth_range=cam_depth_range,
  191. constant_std=constant_std,
  192. imread_flag=imread_flag,
  193. )
  194. @register("ResizeImage")
  195. def build_resize_image(
  196. self,
  197. img_scale=None,
  198. multiscale_mode="range",
  199. ratio_range=None,
  200. keep_ratio=True,
  201. bbox_clip_border=True,
  202. backend="cv2",
  203. override=False,
  204. ):
  205. return "ResizeImage", ResizeImage(
  206. img_scale=img_scale,
  207. multiscale_mode=multiscale_mode,
  208. ratio_range=ratio_range,
  209. keep_ratio=keep_ratio,
  210. bbox_clip_border=bbox_clip_border,
  211. backend=backend,
  212. override=override,
  213. )
  214. @register("NormalizeImage")
  215. def build_normalize_image(self, mean, std, to_rgb=True):
  216. return "NormalizeImage", NormalizeImage(mean=mean, std=std, to_rgb=to_rgb)
  217. @register("PadImage")
  218. def build_pad_image(self, size=None, size_divisor=None, pad_val=0):
  219. return "PadImage", PadImage(
  220. size=size, size_divisor=size_divisor, pad_val=pad_val
  221. )
  222. @register("SampleFilterByKey")
  223. def build_sample_filter_by_key(
  224. self,
  225. keys,
  226. meta_keys=(
  227. "filename",
  228. "ori_shape",
  229. "img_shape",
  230. "lidar2img",
  231. "depth2img",
  232. "cam2img",
  233. "pad_shape",
  234. "scale_factor",
  235. "flip",
  236. "pcd_horizontal_flip",
  237. "pcd_vertical_flip",
  238. "box_type_3d",
  239. "img_norm_cfg",
  240. "pcd_trans",
  241. "sample_idx",
  242. "pcd_scale_factor",
  243. "pcd_rotation",
  244. "pts_filename",
  245. "transformation_3d_flow",
  246. ),
  247. ):
  248. return "SampleFilterByKey", SampleFilterByKey(keys=keys, meta_keys=meta_keys)
  249. @register("GetInferInput")
  250. def build_get_infer_input(self):
  251. return "GetInferInput", GetInferInput()
  252. def apply(self, input: Any, **kwargs) -> Iterator[Any]:
  253. """
  254. Do predicting with the input data and yields predictions.
  255. Args:
  256. input (Any): The input data to be predicted.
  257. Yields:
  258. Iterator[Any]: An iterator yielding prediction results.
  259. """
  260. try:
  261. for batch_data in self.batch_sampler(input):
  262. prediction = self.process(batch_data, **kwargs)
  263. prediction = PredictionWrap(prediction, len(batch_data))
  264. for idx in range(len(batch_data)):
  265. yield self.result_class(prediction.get_by_idx(idx))
  266. except Exception as e:
  267. raise e
  268. finally:
  269. shutil.rmtree(self.temp_dir)