processors.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. import numbers
  15. import cv2
  16. import numpy as np
  17. from typing import Generic, List, Optional
  18. import lazy_paddle as paddle
  19. from ...utils.io import ImageReader
  20. from ....utils import logging
  21. from ...common.reader.det_3d_reader import Sample
  22. from ...utils.benchmark import benchmark
  23. cv2_interp_codes = {
  24. "nearest": cv2.INTER_NEAREST,
  25. "bilinear": cv2.INTER_LINEAR,
  26. "bicubic": cv2.INTER_CUBIC,
  27. "area": cv2.INTER_AREA,
  28. "lanczos": cv2.INTER_LANCZOS4,
  29. }
  30. class LoadPointsFromFile:
  31. """Load points from a file and process them according to specified parameters."""
  32. def __init__(
  33. self, load_dim=6, use_dim=[0, 1, 2], shift_height=False, use_color=False
  34. ):
  35. """Initializes the LoadPointsFromFile object.
  36. Args:
  37. load_dim (int): Dimensions loaded in points.
  38. use_dim (list or int): Dimensions used in points. If int, will use a range from 0 to use_dim (exclusive).
  39. shift_height (bool): Whether to shift height values.
  40. use_color (bool): Whether to include color attributes in the loaded points.
  41. """
  42. self.shift_height = shift_height
  43. self.use_color = use_color
  44. if isinstance(use_dim, int):
  45. use_dim = list(range(use_dim))
  46. assert (
  47. max(use_dim) < load_dim
  48. ), f"Expect all used dimensions < {load_dim}, got {use_dim}"
  49. self.load_dim = load_dim
  50. self.use_dim = use_dim
  51. def _load_points(self, pts_filename):
  52. """Private function to load point clouds data from a file.
  53. Args:
  54. pts_filename (str): Path to the point cloud file.
  55. Returns:
  56. numpy.ndarray: Loaded point cloud data.
  57. """
  58. points = np.fromfile(pts_filename, dtype=np.float32)
  59. return points
  60. @benchmark.timeit
  61. def __call__(self, results):
  62. """Call function to load points data from file and process it.
  63. Args:
  64. results (dict): Dictionary containing the 'pts_filename' key with the path to the point cloud file.
  65. Returns:
  66. dict: Updated results dictionary with 'points' key added.
  67. """
  68. pts_filename = results["pts_filename"]
  69. points = self._load_points(pts_filename)
  70. points = points.reshape(-1, self.load_dim)
  71. points = points[:, self.use_dim]
  72. attribute_dims = None
  73. if self.shift_height:
  74. floor_height = np.percentile(points[:, 2], 0.99)
  75. height = points[:, 2] - floor_height
  76. points = np.concatenate(
  77. [points[:, :3], np.expand_dims(height, 1), points[:, 3:]], 1
  78. )
  79. attribute_dims = dict(height=3)
  80. if self.use_color:
  81. assert len(self.use_dim) >= 6
  82. if attribute_dims is None:
  83. attribute_dims = dict()
  84. attribute_dims.update(
  85. dict(
  86. color=[
  87. points.shape[1] - 3,
  88. points.shape[1] - 2,
  89. points.shape[1] - 1,
  90. ]
  91. )
  92. )
  93. results["points"] = points
  94. return results
  95. class LoadPointsFromMultiSweeps(object):
  96. """Load points from multiple sweeps.This is usually used for nuScenes dataset to utilize previous sweeps."""
  97. def __init__(
  98. self,
  99. sweeps_num=10,
  100. load_dim=5,
  101. use_dim=[0, 1, 2, 4],
  102. pad_empty_sweeps=False,
  103. remove_close=False,
  104. test_mode=False,
  105. point_cloud_angle_range=None,
  106. ):
  107. """Initializes the LoadPointsFromMultiSweeps object
  108. Args:
  109. sweeps_num (int): Number of sweeps. Defaults to 10.
  110. load_dim (int): Dimension number of the loaded points. Defaults to 5.
  111. use_dim (list[int]): Which dimension to use. Defaults to [0, 1, 2, 4].
  112. for more details. Defaults to dict(backend='disk').
  113. pad_empty_sweeps (bool): Whether to repeat keyframe when
  114. sweeps is empty. Defaults to False.
  115. remove_close (bool): Whether to remove close points.
  116. Defaults to False.
  117. test_mode (bool): If test_model=True used for testing, it will not
  118. randomly sample sweeps but select the nearest N frames.
  119. Defaults to False.
  120. """
  121. self.load_dim = load_dim
  122. self.sweeps_num = sweeps_num
  123. self.use_dim = use_dim
  124. self.pad_empty_sweeps = pad_empty_sweeps
  125. self.remove_close = remove_close
  126. self.test_mode = test_mode
  127. if point_cloud_angle_range is not None:
  128. self.filter_by_angle = True
  129. self.point_cloud_angle_range = point_cloud_angle_range
  130. print(point_cloud_angle_range)
  131. else:
  132. self.filter_by_angle = False
  133. # self.point_cloud_angle_range = point_cloud_angle_range
  134. def _load_points(self, pts_filename):
  135. """Private function to load point clouds data.
  136. Args:
  137. pts_filename (str): Filename of point clouds data.
  138. Returns:
  139. np.ndarray: An array containing point clouds data.
  140. """
  141. points = np.fromfile(pts_filename, dtype=np.float32)
  142. return points
  143. def _remove_close(self, points, radius=1.0):
  144. """Removes point too close within a certain radius from origin.
  145. Args:
  146. points (np.ndarray): Sweep points.
  147. radius (float): Radius below which points are removed.
  148. Defaults to 1.0.
  149. Returns:
  150. np.ndarray: Points after removing.
  151. """
  152. if isinstance(points, np.ndarray):
  153. points_numpy = points
  154. else:
  155. raise NotImplementedError
  156. x_filt = np.abs(points_numpy[:, 0]) < radius
  157. y_filt = np.abs(points_numpy[:, 1]) < radius
  158. not_close = np.logical_not(np.logical_and(x_filt, y_filt))
  159. return points[not_close]
  160. def filter_point_by_angle(self, points):
  161. """
  162. Filters points based on their angle in relation to the origin.
  163. Args:
  164. points (np.ndarray): An array of points with shape (N, 2), where each row
  165. is a point in 2D space.
  166. Returns:
  167. np.ndarray: A filtered array of points that fall within the specified
  168. angle range.
  169. """
  170. if isinstance(points, np.ndarray):
  171. points_numpy = points
  172. else:
  173. raise NotImplementedError
  174. pts_phi = (
  175. np.arctan(points_numpy[:, 0] / points_numpy[:, 1])
  176. + (points_numpy[:, 1] < 0) * np.pi
  177. + np.pi * 2
  178. ) % (np.pi * 2)
  179. pts_phi[pts_phi > np.pi] -= np.pi * 2
  180. pts_phi = pts_phi / np.pi * 180
  181. assert np.all(-180 <= pts_phi) and np.all(pts_phi <= 180)
  182. filt = np.logical_and(
  183. pts_phi >= self.point_cloud_angle_range[0],
  184. pts_phi <= self.point_cloud_angle_range[1],
  185. )
  186. return points[filt]
  187. @benchmark.timeit
  188. def __call__(self, results):
  189. """Call function to load multi-sweep point clouds from files.
  190. Args:
  191. results (dict): Result dict containing multi-sweep point cloud \
  192. filenames.
  193. Returns:
  194. dict: The result dict containing the multi-sweep points data. \
  195. Added key and value are described below.
  196. - points (np.ndarray): Multi-sweep point cloud arrays.
  197. """
  198. points = results["points"]
  199. points[:, 4] = 0
  200. sweep_points_list = [points]
  201. ts = results["timestamp"]
  202. if self.pad_empty_sweeps and len(results["sweeps"]) == 0:
  203. for i in range(self.sweeps_num):
  204. if self.remove_close:
  205. sweep_points_list.append(self._remove_close(points))
  206. else:
  207. sweep_points_list.append(points)
  208. else:
  209. if len(results["sweeps"]) <= self.sweeps_num:
  210. choices = np.arange(len(results["sweeps"]))
  211. elif self.test_mode:
  212. choices = np.arange(self.sweeps_num)
  213. else:
  214. choices = np.random.choice(
  215. len(results["sweeps"]), self.sweeps_num, replace=False
  216. )
  217. for idx in choices:
  218. sweep = results["sweeps"][idx]
  219. points_sweep = self._load_points(sweep["data_path"])
  220. points_sweep = np.copy(points_sweep).reshape(-1, self.load_dim)
  221. if self.remove_close:
  222. points_sweep = self._remove_close(points_sweep)
  223. sweep_ts = sweep["timestamp"] / 1e6
  224. points_sweep[:, :3] = (
  225. points_sweep[:, :3] @ sweep["sensor2lidar_rotation"].T
  226. )
  227. points_sweep[:, :3] += sweep["sensor2lidar_translation"]
  228. points_sweep[:, 4] = ts - sweep_ts
  229. # points_sweep = points.new_point(points_sweep)
  230. sweep_points_list.append(points_sweep)
  231. points = np.concatenate(sweep_points_list, axis=0)
  232. if self.filter_by_angle:
  233. points = self.filter_point_by_angle(points)
  234. points = points[:, self.use_dim]
  235. results["points"] = points
  236. return results
  237. class LoadMultiViewImageFromFiles:
  238. """Load multi-view images from files."""
  239. def __init__(
  240. self,
  241. to_float32=False,
  242. project_pts_to_img_depth=False,
  243. cam_depth_range=[4.0, 45.0, 1.0],
  244. constant_std=0.5,
  245. imread_flag=-1,
  246. ):
  247. """
  248. Initializes the LoadMultiViewImageFromFiles object.
  249. Args:
  250. to_float32 (bool): Whether to convert the loaded images to float32. Default: False.
  251. project_pts_to_img_depth (bool): Whether to project points to image depth. Default: False.
  252. cam_depth_range (list): Camera depth range in the format [min, max, focal]. Default: [4.0, 45.0, 1.0].
  253. constant_std (float): Constant standard deviation for normalization. Default: 0.5.
  254. imread_flag (int): Flag determining the color type of the loaded image.
  255. - -1: cv2.IMREAD_UNCHANGED
  256. - 0: cv2.IMREAD_GRAYSCALE
  257. - 1: cv2.IMREAD_COLOR
  258. Default: -1.
  259. """
  260. self.to_float32 = to_float32
  261. self.project_pts_to_img_depth = project_pts_to_img_depth
  262. self.cam_depth_range = cam_depth_range
  263. self.constant_std = constant_std
  264. self.imread_flag = imread_flag
  265. @benchmark.timeit
  266. def __call__(self, sample):
  267. """
  268. Call method to load multi-view image from files and update the sample dictionary.
  269. Args:
  270. sample (dict): Dictionary containing the image filename key.
  271. Returns:
  272. dict: Updated sample dictionary with loaded images and additional information.
  273. """
  274. filename = sample["img_filename"]
  275. img = np.stack(
  276. [cv2.imread(name, self.imread_flag) for name in filename], axis=-1
  277. )
  278. if self.to_float32:
  279. img = img.astype(np.float32)
  280. sample["filename"] = filename
  281. sample["img"] = [img[..., i] for i in range(img.shape[-1])]
  282. sample["img_shape"] = img.shape
  283. sample["ori_shape"] = img.shape
  284. sample["pad_shape"] = img.shape
  285. # sample['scale_factor'] = 1.0
  286. num_channels = 1 if len(img.shape) < 3 else img.shape[2]
  287. sample["img_norm_cfg"] = dict(
  288. mean=np.zeros(num_channels, dtype=np.float32),
  289. std=np.ones(num_channels, dtype=np.float32),
  290. to_rgb=False,
  291. )
  292. sample["img_fields"] = ["img"]
  293. return sample
  294. class ResizeImage:
  295. """Resize images & bbox & mask."""
  296. def __init__(
  297. self,
  298. img_scale=None,
  299. multiscale_mode="range",
  300. ratio_range=None,
  301. keep_ratio=True,
  302. bbox_clip_border=True,
  303. backend="cv2",
  304. override=False,
  305. ):
  306. """Initializes the ResizeImage object.
  307. Args:
  308. img_scale (list or int, optional): The scale of the image. If a single integer is provided, it will be converted to a list. Defaults to None.
  309. multiscale_mode (str): The mode for multiscale resizing. Can be "value" or "range". Defaults to "range".
  310. ratio_range (list, optional): The range of image aspect ratios. Only used when img_scale is a single value. Defaults to None.
  311. keep_ratio (bool): Whether to keep the aspect ratio when resizing. Defaults to True.
  312. bbox_clip_border (bool): Whether to clip the bounding box to the image border. Defaults to True.
  313. backend (str): The backend to use for image resizing. Can be "cv2". Defaults to "cv2".
  314. override (bool): Whether to override certain resize parameters. Note: This option needs refactoring. Defaults to False.
  315. """
  316. if img_scale is None:
  317. self.img_scale = None
  318. else:
  319. if isinstance(img_scale, list):
  320. self.img_scale = img_scale
  321. else:
  322. self.img_scale = [img_scale]
  323. if ratio_range is not None:
  324. # mode 1: given a scale and a range of image ratio
  325. assert len(self.img_scale) == 1
  326. else:
  327. # mode 2: given multiple scales or a range of scales
  328. assert multiscale_mode in ["value", "range"]
  329. self.backend = backend
  330. self.multiscale_mode = multiscale_mode
  331. self.ratio_range = ratio_range
  332. self.keep_ratio = keep_ratio
  333. # TODO: refactor the override option in Resize
  334. self.override = override
  335. self.bbox_clip_border = bbox_clip_border
  336. @staticmethod
  337. def random_select(img_scales):
  338. """Randomly select an img_scale from the given list of candidates.
  339. Args:
  340. img_scales (list): A list of image scales to choose from.
  341. Returns:
  342. tuple: A tuple containing the selected image scale and its index in the list.
  343. """
  344. scale_idx = np.random.randint(len(img_scales))
  345. img_scale = img_scales[scale_idx]
  346. return img_scale, scale_idx
  347. @staticmethod
  348. def random_sample(img_scales):
  349. """
  350. Randomly sample an img_scale when `multiscale_mode` is set to 'range'.
  351. Args:
  352. img_scales (list of tuples): A list of tuples, where each tuple contains
  353. the minimum and maximum scale dimensions for an image.
  354. Returns:
  355. tuple: A tuple containing the randomly sampled img_scale (long_edge, short_edge)
  356. and None (to maintain function signature compatibility).
  357. """
  358. img_scale_long = [max(s) for s in img_scales]
  359. img_scale_short = [min(s) for s in img_scales]
  360. long_edge = np.random.randint(min(img_scale_long), max(img_scale_long) + 1)
  361. short_edge = np.random.randint(min(img_scale_short), max(img_scale_short) + 1)
  362. img_scale = (long_edge, short_edge)
  363. return img_scale, None
  364. @staticmethod
  365. def random_sample_ratio(img_scale, ratio_range):
  366. """
  367. Randomly sample an img_scale based on the specified ratio_range.
  368. Args:
  369. img_scale (list): A list of two integers representing the minimum and maximum
  370. scale for the image.
  371. ratio_range (tuple): A tuple of two floats representing the minimum and maximum
  372. ratio for sampling the img_scale.
  373. Returns:
  374. tuple: A tuple containing the sampled scale (as a tuple of two integers)
  375. and None.
  376. """
  377. assert isinstance(img_scale, list) and len(img_scale) == 2
  378. min_ratio, max_ratio = ratio_range
  379. assert min_ratio <= max_ratio
  380. ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio
  381. scale = int(img_scale[0] * ratio), int(img_scale[1] * ratio)
  382. return scale, None
  383. def _random_scale(self, results):
  384. """Randomly sample an img_scale according to `ratio_range` and `multiscale_mode`.
  385. Args:
  386. results (dict): A dictionary to store the sampled scale and its index.
  387. Returns:
  388. None. The sampled scale and its index are stored in `results` dictionary.
  389. """
  390. if self.ratio_range is not None:
  391. scale, scale_idx = self.random_sample_ratio(
  392. self.img_scale[0], self.ratio_range
  393. )
  394. elif len(self.img_scale) == 1:
  395. scale, scale_idx = self.img_scale[0], 0
  396. elif self.multiscale_mode == "range":
  397. scale, scale_idx = self.random_sample(self.img_scale)
  398. elif self.multiscale_mode == "value":
  399. scale, scale_idx = self.random_select(self.img_scale)
  400. else:
  401. raise NotImplementedError
  402. results["scale"] = scale
  403. results["scale_idx"] = scale_idx
  404. def _resize_img(self, results):
  405. """Resize images based on the scale factor provided in ``results['scale']`` while maintaining the aspect ratio if ``self.keep_ratio`` is True.
  406. Args:
  407. results (dict): A dictionary containing image fields and their corresponding scales.
  408. Returns:
  409. None. The ``results`` dictionary is modified in place with resized images and additional fields like `img_shape`, `pad_shape`, `scale_factor`, and `keep_ratio`.
  410. """
  411. for key in results.get("img_fields", ["img"]):
  412. for idx in range(len(results["img"])):
  413. if self.keep_ratio:
  414. img, scale_factor = self.imrescale(
  415. results[key][idx],
  416. results["scale"],
  417. interpolation="bilinear" if key == "img" else "nearest",
  418. return_scale=True,
  419. backend=self.backend,
  420. )
  421. new_h, new_w = img.shape[:2]
  422. h, w = results[key][idx].shape[:2]
  423. w_scale = new_w / w
  424. h_scale = new_h / h
  425. else:
  426. raise NotImplementedError
  427. results[key][idx] = img
  428. scale_factor = np.array(
  429. [w_scale, h_scale, w_scale, h_scale], dtype=np.float32
  430. )
  431. results["img_shape"] = img.shape
  432. # in case that there is no padding
  433. results["pad_shape"] = img.shape
  434. results["scale_factor"] = scale_factor
  435. results["keep_ratio"] = self.keep_ratio
  436. def rescale_size(self, old_size, scale, return_scale=False):
  437. """
  438. Calculate the new size to be rescaled to based on the given scale.
  439. Args:
  440. old_size (tuple): A tuple containing the width and height of the original size.
  441. scale (float, int, or list of int): The scale factor or a list of integers representing the maximum and minimum allowed size.
  442. return_scale (bool): Whether to return the scale factor along with the new size.
  443. Returns:
  444. tuple: A tuple containing the new size and optionally the scale factor if return_scale is True.
  445. """
  446. w, h = old_size
  447. if isinstance(scale, (float, int)):
  448. if scale <= 0:
  449. raise ValueError(f"Invalid scale {scale}, must be positive.")
  450. scale_factor = scale
  451. elif isinstance(scale, list):
  452. max_long_edge = max(scale)
  453. max_short_edge = min(scale)
  454. scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w))
  455. else:
  456. raise TypeError(
  457. f"Scale must be a number or list of int, but got {type(scale)}"
  458. )
  459. def _scale_size(size, scale):
  460. if isinstance(scale, (float, int)):
  461. scale = (scale, scale)
  462. w, h = size
  463. return int(w * float(scale[0]) + 0.5), int(h * float(scale[1]) + 0.5)
  464. new_size = _scale_size((w, h), scale_factor)
  465. if return_scale:
  466. return new_size, scale_factor
  467. else:
  468. return new_size
  469. def imrescale(
  470. self, img, scale, return_scale=False, interpolation="bilinear", backend=None
  471. ):
  472. """Resize image while keeping the aspect ratio.
  473. Args:
  474. img (numpy.ndarray): The input image.
  475. scale (float): The scaling factor.
  476. return_scale (bool): Whether to return the scaling factor along with the resized image.
  477. interpolation (str): The interpolation method to use. Defaults to 'bilinear'.
  478. backend (str): The backend to use for resizing. Defaults to None.
  479. Returns:
  480. tuple or numpy.ndarray: The resized image, and optionally the scaling factor.
  481. """
  482. h, w = img.shape[:2]
  483. new_size, scale_factor = self.rescale_size((w, h), scale, return_scale=True)
  484. rescaled_img = self.imresize(
  485. img, new_size, interpolation=interpolation, backend=backend
  486. )
  487. if return_scale:
  488. return rescaled_img, scale_factor
  489. else:
  490. return rescaled_img
  491. def imresize(
  492. self,
  493. img,
  494. size,
  495. return_scale=False,
  496. interpolation="bilinear",
  497. out=None,
  498. backend=None,
  499. ):
  500. """Resize an image to a given size.
  501. Args:
  502. img (numpy.ndarray): The input image to be resized.
  503. size (tuple): The new size for the image as (height, width).
  504. return_scale (bool): Whether to return the scaling factors along with the resized image.
  505. interpolation (str): The interpolation method to use. Default is 'bilinear'.
  506. out (numpy.ndarray, optional): Output array. If provided, it must have the same shape and dtype as the output array.
  507. backend (str, optional): The backend to use for resizing. Supported backends are 'cv2' and 'pillow'.
  508. Returns:
  509. numpy.ndarray or tuple: The resized image. If return_scale is True, returns a tuple containing the resized image and the scaling factors (w_scale, h_scale).
  510. """
  511. h, w = img.shape[:2]
  512. if backend not in ["cv2", "pillow"]:
  513. raise ValueError(
  514. f"backend: {backend} is not supported for resize."
  515. f"Supported backends are 'cv2', 'pillow'"
  516. )
  517. if backend == "pillow":
  518. raise NotImplementedError
  519. else:
  520. resized_img = cv2.resize(
  521. img, size, dst=out, interpolation=cv2_interp_codes[interpolation]
  522. )
  523. if not return_scale:
  524. return resized_img
  525. else:
  526. w_scale = size[0] / w
  527. h_scale = size[1] / h
  528. return resized_img, w_scale, h_scale
  529. def _resize_bboxes(self, results):
  530. """Resize bounding boxes with `results['scale_factor']`.
  531. Args:
  532. results (dict): A dictionary containing the bounding boxes and other related information.
  533. """
  534. for key in results.get("bbox_fields", []):
  535. bboxes = results[key] * results["scale_factor"]
  536. if self.bbox_clip_border:
  537. img_shape = results["img_shape"]
  538. bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
  539. bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
  540. results[key] = bboxes
  541. def _resize_masks(self, results):
  542. """Resize masks with ``results['scale']``"""
  543. raise NotImplementedError
  544. def _resize_seg(self, results):
  545. """Resize semantic segmentation map with ``results['scale']``."""
  546. raise NotImplementedError
  547. @benchmark.timeit
  548. def __call__(self, results):
  549. """Call function to resize images, bounding boxes, masks, and semantic segmentation maps according to the provided scale or scale factor.
  550. Args:
  551. results (dict): A dictionary containing the input data, including 'img', 'scale', and optionally 'scale_factor'.
  552. Returns:
  553. dict: A dictionary with the resized data.
  554. """
  555. if "scale" not in results:
  556. if "scale_factor" in results:
  557. img_shape = results["img"][0].shape[:2]
  558. scale_factor = results["scale_factor"]
  559. assert isinstance(scale_factor, float)
  560. results["scale"] = list(
  561. [int(x * scale_factor) for x in img_shape][::-1]
  562. )
  563. else:
  564. self._random_scale(results)
  565. else:
  566. if not self.override:
  567. assert (
  568. "scale_factor" not in results
  569. ), "scale and scale_factor cannot be both set."
  570. else:
  571. results.pop("scale")
  572. if "scale_factor" in results:
  573. results.pop("scale_factor")
  574. self._random_scale(results)
  575. self._resize_img(results)
  576. self._resize_bboxes(results)
  577. return results
  578. class NormalizeImage:
  579. """Normalize the image."""
  580. """Normalize an image by subtracting the mean and dividing by the standard deviation.
  581. Args:
  582. mean (list or tuple): Mean values for each channel.
  583. std (list or tuple): Standard deviation values for each channel.
  584. to_rgb (bool): Whether to convert the image from BGR to RGB.
  585. """
  586. def __init__(self, mean, std, to_rgb=True):
  587. """Initializes the NormalizeImage class with mean, std, and to_rgb parameters."""
  588. self.mean = np.array(mean, dtype=np.float32)
  589. self.std = np.array(std, dtype=np.float32)
  590. self.to_rgb = to_rgb
  591. def _imnormalize(self, img, mean, std, to_rgb=True):
  592. """Normalize the given image inplace.
  593. Args:
  594. img (numpy.ndarray): The image to normalize.
  595. mean (numpy.ndarray): Mean values for normalization.
  596. std (numpy.ndarray): Standard deviation values for normalization.
  597. to_rgb (bool): Whether to convert the image from BGR to RGB.
  598. Returns:
  599. numpy.ndarray: The normalized image.
  600. """
  601. img = img.copy().astype(np.float32)
  602. mean = np.float64(mean.reshape(1, -1))
  603. stdinv = 1 / np.float64(std.reshape(1, -1))
  604. if to_rgb:
  605. cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) # inplace
  606. cv2.subtract(img, mean, img) # inplace
  607. cv2.multiply(img, stdinv, img) # inplace
  608. return img
  609. @benchmark.timeit
  610. def __call__(self, results):
  611. """Call method to normalize images in the results dictionary.
  612. Args:
  613. results (dict): A dictionary containing image fields to normalize.
  614. Returns:
  615. dict: The results dictionary with normalized images.
  616. """
  617. for key in results.get("img_fields", ["img"]):
  618. if key == "img_depth":
  619. continue
  620. for idx in range(len(results["img"])):
  621. results[key][idx] = self._imnormalize(
  622. results[key][idx], self.mean, self.std, self.to_rgb
  623. )
  624. results["img_norm_cfg"] = dict(mean=self.mean, std=self.std, to_rgb=self.to_rgb)
  625. return results
  626. class PadImage(object):
  627. """Pad the image & mask."""
  628. def __init__(self, size=None, size_divisor=None, pad_val=0):
  629. self.size = size
  630. self.size_divisor = size_divisor
  631. self.pad_val = pad_val
  632. # only one of size and size_divisor should be valid
  633. assert size is not None or size_divisor is not None
  634. assert size is None or size_divisor is None
  635. def impad(
  636. self, img, *, shape=None, padding=None, pad_val=0, padding_mode="constant"
  637. ):
  638. """Pad the given image to a certain shape or pad on all sides
  639. Args:
  640. img (numpy.ndarray): The input image to be padded.
  641. shape (tuple, optional): Desired output shape in the form (height, width). One of shape or padding must be specified.
  642. padding (int, tuple, optional): Number of pixels to pad on each side of the image. If a single int is provided this
  643. is used to pad all sides with this value. If a tuple of length 2 is provided this is interpreted as (top_bottom, left_right).
  644. If a tuple of length 4 is provided this is interpreted as (top, right, bottom, left).
  645. pad_val (int, list, optional): Pixel value used for padding. If a list is provided, it must have the same length as the
  646. last dimension of the input image. Defaults to 0.
  647. padding_mode (str, optional): Padding mode to use. One of 'constant', 'edge', 'reflect', 'symmetric'.
  648. Defaults to 'constant'.
  649. Returns:
  650. numpy.ndarray: The padded image.
  651. """
  652. assert (shape is not None) ^ (padding is not None)
  653. if shape is not None:
  654. padding = [0, 0, shape[1] - img.shape[1], shape[0] - img.shape[0]]
  655. # check pad_val
  656. if isinstance(pad_val, list):
  657. assert len(pad_val) == img.shape[-1]
  658. elif not isinstance(pad_val, numbers.Number):
  659. raise TypeError(
  660. "pad_val must be a int or a list. " f"But received {type(pad_val)}"
  661. )
  662. # check padding
  663. if isinstance(padding, list) and len(padding) in [2, 4]:
  664. if len(padding) == 2:
  665. padding = [padding[0], padding[1], padding[0], padding[1]]
  666. elif isinstance(padding, numbers.Number):
  667. padding = [padding, padding, padding, padding]
  668. else:
  669. raise ValueError(
  670. "Padding must be a int or a 2, or 4 element list."
  671. f"But received {padding}"
  672. )
  673. # check padding mode
  674. assert padding_mode in ["constant", "edge", "reflect", "symmetric"]
  675. border_type = {
  676. "constant": cv2.BORDER_CONSTANT,
  677. "edge": cv2.BORDER_REPLICATE,
  678. "reflect": cv2.BORDER_REFLECT_101,
  679. "symmetric": cv2.BORDER_REFLECT,
  680. }
  681. img = cv2.copyMakeBorder(
  682. img,
  683. padding[1],
  684. padding[3],
  685. padding[0],
  686. padding[2],
  687. border_type[padding_mode],
  688. value=pad_val,
  689. )
  690. return img
  691. def impad_to_multiple(self, img, divisor, pad_val=0):
  692. """
  693. Pad an image to ensure each edge length is a multiple of a given number.
  694. Args:
  695. img (numpy.ndarray): The input image.
  696. divisor (int): The number to which each edge length should be a multiple.
  697. pad_val (int, optional): The value to pad the image with. Defaults to 0.
  698. Returns:
  699. numpy.ndarray: The padded image.
  700. """
  701. pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor
  702. pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor
  703. return self.impad(img, shape=(pad_h, pad_w), pad_val=pad_val)
  704. def _pad_img(self, results):
  705. """
  706. Pad images according to ``self.size`` or adjust their shapes to be multiples of ``self.size_divisor``.
  707. Args:
  708. results (dict): A dictionary containing image data, with 'img_fields' as an optional key
  709. pointing to a list of image field names.
  710. """
  711. for key in results.get("img_fields", ["img"]):
  712. if self.size is not None:
  713. padded_img = self.impad(
  714. results[key], shape=self.size, pad_val=self.pad_val
  715. )
  716. elif self.size_divisor is not None:
  717. for idx in range(len(results[key])):
  718. padded_img = self.impad_to_multiple(
  719. results[key][idx], self.size_divisor, pad_val=self.pad_val
  720. )
  721. results[key][idx] = padded_img
  722. results["pad_shape"] = padded_img.shape
  723. results["pad_fixed_size"] = self.size
  724. results["pad_size_divisor"] = self.size_divisor
  725. def _pad_masks(self, results):
  726. """Pad masks according to ``results['pad_shape']``."""
  727. raise NotImplementedError
  728. def _pad_seg(self, results):
  729. """Pad semantic segmentation map according to ``results['pad_shape']``."""
  730. raise NotImplementedError
  731. @benchmark.timeit
  732. def __call__(self, results):
  733. """Call function to pad images, masks, semantic segmentation maps."""
  734. self._pad_img(results)
  735. return results
  736. class SampleFilterByKey:
  737. """Collect data from the loader relevant to the specific task."""
  738. def __init__(
  739. self,
  740. keys,
  741. meta_keys=(
  742. "filename",
  743. "ori_shape",
  744. "img_shape",
  745. "lidar2img",
  746. "depth2img",
  747. "cam2img",
  748. "pad_shape",
  749. "scale_factor",
  750. "flip",
  751. "pcd_horizontal_flip",
  752. "pcd_vertical_flip",
  753. "box_type_3d",
  754. "img_norm_cfg",
  755. "pcd_trans",
  756. "sample_idx",
  757. "pcd_scale_factor",
  758. "pcd_rotation",
  759. "pts_filename",
  760. "transformation_3d_flow",
  761. ),
  762. ):
  763. self.keys = keys
  764. self.meta_keys = meta_keys
  765. @benchmark.timeit
  766. def __call__(self, sample):
  767. """Call function to filter sample by keys. The keys in `meta_keys` are used to filter metadata from the input sample.
  768. Args:
  769. sample (Sample): The input sample to be filtered.
  770. Returns:
  771. Sample: A new Sample object containing only the filtered metadata and specified keys.
  772. """
  773. filtered_sample = Sample(path=sample.path, modality=sample.modality)
  774. filtered_sample.meta.id = sample.meta.id
  775. img_metas = {}
  776. for key in self.meta_keys:
  777. if key in sample:
  778. img_metas[key] = sample[key]
  779. filtered_sample["img_metas"] = img_metas
  780. for key in self.keys:
  781. filtered_sample[key] = sample[key]
  782. return filtered_sample
  783. class GetInferInput:
  784. """Collect infer input data from transformed sample"""
  785. def collate_fn(self, batch):
  786. sample = batch[0]
  787. collated_batch = {}
  788. collated_fields = [
  789. "img",
  790. "points",
  791. "img_metas",
  792. "gt_bboxes_3d",
  793. "gt_labels_3d",
  794. "modality",
  795. "meta",
  796. "idx",
  797. "img_depth",
  798. ]
  799. for k in list(sample.keys()):
  800. if k not in collated_fields:
  801. continue
  802. if k == "img":
  803. collated_batch[k] = np.stack([elem[k] for elem in batch], axis=0)
  804. elif k == "img_depth":
  805. collated_batch[k] = np.stack(
  806. [np.stack(elem[k], axis=0) for elem in batch], axis=0
  807. )
  808. else:
  809. collated_batch[k] = [elem[k] for elem in batch]
  810. return collated_batch
  811. @benchmark.timeit
  812. def __call__(self, sample):
  813. """Call function to infer input data from transformed sample
  814. Args:
  815. sample (Sample): The input sample data.
  816. Returns:
  817. infer_input (list): A list containing all the input data for inference.
  818. sample_id (str): token id of the input sample.
  819. """
  820. if sample.modality == "multimodal" or sample.modality == "multiview":
  821. if "img" in sample.keys():
  822. sample.img = np.stack(
  823. [img.transpose(2, 0, 1) for img in sample.img], axis=0
  824. )
  825. sample = self.collate_fn([sample])
  826. infer_input = []
  827. img = sample.get("img", None)[0]
  828. infer_input.append(img.astype(np.float32))
  829. lidar2img = np.stack(sample["img_metas"][0]["lidar2img"]).astype(np.float32)
  830. infer_input.append(lidar2img)
  831. points = sample.get("points", None)[0]
  832. infer_input.append(points.astype(np.float32))
  833. img_metas = {
  834. "input_lidar_path": sample["img_metas"][0]["pts_filename"],
  835. "input_img_paths": sample["img_metas"][0]["filename"],
  836. "sample_id": sample["img_metas"][0]["sample_idx"],
  837. }
  838. return infer_input, img_metas