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. @benchmark.timeit
  31. class LoadPointsFromFile:
  32. """Load points from a file and process them according to specified parameters."""
  33. def __init__(
  34. self, load_dim=6, use_dim=[0, 1, 2], shift_height=False, use_color=False
  35. ):
  36. """Initializes the LoadPointsFromFile object.
  37. Args:
  38. load_dim (int): Dimensions loaded in points.
  39. use_dim (list or int): Dimensions used in points. If int, will use a range from 0 to use_dim (exclusive).
  40. shift_height (bool): Whether to shift height values.
  41. use_color (bool): Whether to include color attributes in the loaded points.
  42. """
  43. self.shift_height = shift_height
  44. self.use_color = use_color
  45. if isinstance(use_dim, int):
  46. use_dim = list(range(use_dim))
  47. assert (
  48. max(use_dim) < load_dim
  49. ), f"Expect all used dimensions < {load_dim}, got {use_dim}"
  50. self.load_dim = load_dim
  51. self.use_dim = use_dim
  52. def _load_points(self, pts_filename):
  53. """Private function to load point clouds data from a file.
  54. Args:
  55. pts_filename (str): Path to the point cloud file.
  56. Returns:
  57. numpy.ndarray: Loaded point cloud data.
  58. """
  59. points = np.fromfile(pts_filename, dtype=np.float32)
  60. return points
  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. @benchmark.timeit
  96. class LoadPointsFromMultiSweeps(object):
  97. """Load points from multiple sweeps.This is usually used for nuScenes dataset to utilize previous sweeps."""
  98. def __init__(
  99. self,
  100. sweeps_num=10,
  101. load_dim=5,
  102. use_dim=[0, 1, 2, 4],
  103. pad_empty_sweeps=False,
  104. remove_close=False,
  105. test_mode=False,
  106. point_cloud_angle_range=None,
  107. ):
  108. """Initializes the LoadPointsFromMultiSweeps object
  109. Args:
  110. sweeps_num (int): Number of sweeps. Defaults to 10.
  111. load_dim (int): Dimension number of the loaded points. Defaults to 5.
  112. use_dim (list[int]): Which dimension to use. Defaults to [0, 1, 2, 4].
  113. for more details. Defaults to dict(backend='disk').
  114. pad_empty_sweeps (bool): Whether to repeat keyframe when
  115. sweeps is empty. Defaults to False.
  116. remove_close (bool): Whether to remove close points.
  117. Defaults to False.
  118. test_mode (bool): If test_model=True used for testing, it will not
  119. randomly sample sweeps but select the nearest N frames.
  120. Defaults to False.
  121. """
  122. self.load_dim = load_dim
  123. self.sweeps_num = sweeps_num
  124. self.use_dim = use_dim
  125. self.pad_empty_sweeps = pad_empty_sweeps
  126. self.remove_close = remove_close
  127. self.test_mode = test_mode
  128. if point_cloud_angle_range is not None:
  129. self.filter_by_angle = True
  130. self.point_cloud_angle_range = point_cloud_angle_range
  131. print(point_cloud_angle_range)
  132. else:
  133. self.filter_by_angle = False
  134. # self.point_cloud_angle_range = point_cloud_angle_range
  135. def _load_points(self, pts_filename):
  136. """Private function to load point clouds data.
  137. Args:
  138. pts_filename (str): Filename of point clouds data.
  139. Returns:
  140. np.ndarray: An array containing point clouds data.
  141. """
  142. points = np.fromfile(pts_filename, dtype=np.float32)
  143. return points
  144. def _remove_close(self, points, radius=1.0):
  145. """Removes point too close within a certain radius from origin.
  146. Args:
  147. points (np.ndarray): Sweep points.
  148. radius (float): Radius below which points are removed.
  149. Defaults to 1.0.
  150. Returns:
  151. np.ndarray: Points after removing.
  152. """
  153. if isinstance(points, np.ndarray):
  154. points_numpy = points
  155. else:
  156. raise NotImplementedError
  157. x_filt = np.abs(points_numpy[:, 0]) < radius
  158. y_filt = np.abs(points_numpy[:, 1]) < radius
  159. not_close = np.logical_not(np.logical_and(x_filt, y_filt))
  160. return points[not_close]
  161. def filter_point_by_angle(self, points):
  162. """
  163. Filters points based on their angle in relation to the origin.
  164. Args:
  165. points (np.ndarray): An array of points with shape (N, 2), where each row
  166. is a point in 2D space.
  167. Returns:
  168. np.ndarray: A filtered array of points that fall within the specified
  169. angle range.
  170. """
  171. if isinstance(points, np.ndarray):
  172. points_numpy = points
  173. else:
  174. raise NotImplementedError
  175. pts_phi = (
  176. np.arctan(points_numpy[:, 0] / points_numpy[:, 1])
  177. + (points_numpy[:, 1] < 0) * np.pi
  178. + np.pi * 2
  179. ) % (np.pi * 2)
  180. pts_phi[pts_phi > np.pi] -= np.pi * 2
  181. pts_phi = pts_phi / np.pi * 180
  182. assert np.all(-180 <= pts_phi) and np.all(pts_phi <= 180)
  183. filt = np.logical_and(
  184. pts_phi >= self.point_cloud_angle_range[0],
  185. pts_phi <= self.point_cloud_angle_range[1],
  186. )
  187. return points[filt]
  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. @benchmark.timeit
  238. class LoadMultiViewImageFromFiles:
  239. """Load multi-view images from files."""
  240. def __init__(
  241. self,
  242. to_float32=False,
  243. project_pts_to_img_depth=False,
  244. cam_depth_range=[4.0, 45.0, 1.0],
  245. constant_std=0.5,
  246. imread_flag=-1,
  247. ):
  248. """
  249. Initializes the LoadMultiViewImageFromFiles object.
  250. Args:
  251. to_float32 (bool): Whether to convert the loaded images to float32. Default: False.
  252. project_pts_to_img_depth (bool): Whether to project points to image depth. Default: False.
  253. cam_depth_range (list): Camera depth range in the format [min, max, focal]. Default: [4.0, 45.0, 1.0].
  254. constant_std (float): Constant standard deviation for normalization. Default: 0.5.
  255. imread_flag (int): Flag determining the color type of the loaded image.
  256. - -1: cv2.IMREAD_UNCHANGED
  257. - 0: cv2.IMREAD_GRAYSCALE
  258. - 1: cv2.IMREAD_COLOR
  259. Default: -1.
  260. """
  261. self.to_float32 = to_float32
  262. self.project_pts_to_img_depth = project_pts_to_img_depth
  263. self.cam_depth_range = cam_depth_range
  264. self.constant_std = constant_std
  265. self.imread_flag = imread_flag
  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. @benchmark.timeit
  295. class ResizeImage:
  296. """Resize images & bbox & mask."""
  297. def __init__(
  298. self,
  299. img_scale=None,
  300. multiscale_mode="range",
  301. ratio_range=None,
  302. keep_ratio=True,
  303. bbox_clip_border=True,
  304. backend="cv2",
  305. override=False,
  306. ):
  307. """Initializes the ResizeImage object.
  308. Args:
  309. 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.
  310. multiscale_mode (str): The mode for multiscale resizing. Can be "value" or "range". Defaults to "range".
  311. ratio_range (list, optional): The range of image aspect ratios. Only used when img_scale is a single value. Defaults to None.
  312. keep_ratio (bool): Whether to keep the aspect ratio when resizing. Defaults to True.
  313. bbox_clip_border (bool): Whether to clip the bounding box to the image border. Defaults to True.
  314. backend (str): The backend to use for image resizing. Can be "cv2". Defaults to "cv2".
  315. override (bool): Whether to override certain resize parameters. Note: This option needs refactoring. Defaults to False.
  316. """
  317. if img_scale is None:
  318. self.img_scale = None
  319. else:
  320. if isinstance(img_scale, list):
  321. self.img_scale = img_scale
  322. else:
  323. self.img_scale = [img_scale]
  324. if ratio_range is not None:
  325. # mode 1: given a scale and a range of image ratio
  326. assert len(self.img_scale) == 1
  327. else:
  328. # mode 2: given multiple scales or a range of scales
  329. assert multiscale_mode in ["value", "range"]
  330. self.backend = backend
  331. self.multiscale_mode = multiscale_mode
  332. self.ratio_range = ratio_range
  333. self.keep_ratio = keep_ratio
  334. # TODO: refactor the override option in Resize
  335. self.override = override
  336. self.bbox_clip_border = bbox_clip_border
  337. @staticmethod
  338. def random_select(img_scales):
  339. """Randomly select an img_scale from the given list of candidates.
  340. Args:
  341. img_scales (list): A list of image scales to choose from.
  342. Returns:
  343. tuple: A tuple containing the selected image scale and its index in the list.
  344. """
  345. scale_idx = np.random.randint(len(img_scales))
  346. img_scale = img_scales[scale_idx]
  347. return img_scale, scale_idx
  348. @staticmethod
  349. def random_sample(img_scales):
  350. """
  351. Randomly sample an img_scale when `multiscale_mode` is set to 'range'.
  352. Args:
  353. img_scales (list of tuples): A list of tuples, where each tuple contains
  354. the minimum and maximum scale dimensions for an image.
  355. Returns:
  356. tuple: A tuple containing the randomly sampled img_scale (long_edge, short_edge)
  357. and None (to maintain function signature compatibility).
  358. """
  359. img_scale_long = [max(s) for s in img_scales]
  360. img_scale_short = [min(s) for s in img_scales]
  361. long_edge = np.random.randint(min(img_scale_long), max(img_scale_long) + 1)
  362. short_edge = np.random.randint(min(img_scale_short), max(img_scale_short) + 1)
  363. img_scale = (long_edge, short_edge)
  364. return img_scale, None
  365. @staticmethod
  366. def random_sample_ratio(img_scale, ratio_range):
  367. """
  368. Randomly sample an img_scale based on the specified ratio_range.
  369. Args:
  370. img_scale (list): A list of two integers representing the minimum and maximum
  371. scale for the image.
  372. ratio_range (tuple): A tuple of two floats representing the minimum and maximum
  373. ratio for sampling the img_scale.
  374. Returns:
  375. tuple: A tuple containing the sampled scale (as a tuple of two integers)
  376. and None.
  377. """
  378. assert isinstance(img_scale, list) and len(img_scale) == 2
  379. min_ratio, max_ratio = ratio_range
  380. assert min_ratio <= max_ratio
  381. ratio = np.random.random_sample() * (max_ratio - min_ratio) + min_ratio
  382. scale = int(img_scale[0] * ratio), int(img_scale[1] * ratio)
  383. return scale, None
  384. def _random_scale(self, results):
  385. """Randomly sample an img_scale according to `ratio_range` and `multiscale_mode`.
  386. Args:
  387. results (dict): A dictionary to store the sampled scale and its index.
  388. Returns:
  389. None. The sampled scale and its index are stored in `results` dictionary.
  390. """
  391. if self.ratio_range is not None:
  392. scale, scale_idx = self.random_sample_ratio(
  393. self.img_scale[0], self.ratio_range
  394. )
  395. elif len(self.img_scale) == 1:
  396. scale, scale_idx = self.img_scale[0], 0
  397. elif self.multiscale_mode == "range":
  398. scale, scale_idx = self.random_sample(self.img_scale)
  399. elif self.multiscale_mode == "value":
  400. scale, scale_idx = self.random_select(self.img_scale)
  401. else:
  402. raise NotImplementedError
  403. results["scale"] = scale
  404. results["scale_idx"] = scale_idx
  405. def _resize_img(self, results):
  406. """Resize images based on the scale factor provided in ``results['scale']`` while maintaining the aspect ratio if ``self.keep_ratio`` is True.
  407. Args:
  408. results (dict): A dictionary containing image fields and their corresponding scales.
  409. Returns:
  410. None. The ``results`` dictionary is modified in place with resized images and additional fields like `img_shape`, `pad_shape`, `scale_factor`, and `keep_ratio`.
  411. """
  412. for key in results.get("img_fields", ["img"]):
  413. for idx in range(len(results["img"])):
  414. if self.keep_ratio:
  415. img, scale_factor = self.imrescale(
  416. results[key][idx],
  417. results["scale"],
  418. interpolation="bilinear" if key == "img" else "nearest",
  419. return_scale=True,
  420. backend=self.backend,
  421. )
  422. new_h, new_w = img.shape[:2]
  423. h, w = results[key][idx].shape[:2]
  424. w_scale = new_w / w
  425. h_scale = new_h / h
  426. else:
  427. raise NotImplementedError
  428. results[key][idx] = img
  429. scale_factor = np.array(
  430. [w_scale, h_scale, w_scale, h_scale], dtype=np.float32
  431. )
  432. results["img_shape"] = img.shape
  433. # in case that there is no padding
  434. results["pad_shape"] = img.shape
  435. results["scale_factor"] = scale_factor
  436. results["keep_ratio"] = self.keep_ratio
  437. def rescale_size(self, old_size, scale, return_scale=False):
  438. """
  439. Calculate the new size to be rescaled to based on the given scale.
  440. Args:
  441. old_size (tuple): A tuple containing the width and height of the original size.
  442. scale (float, int, or list of int): The scale factor or a list of integers representing the maximum and minimum allowed size.
  443. return_scale (bool): Whether to return the scale factor along with the new size.
  444. Returns:
  445. tuple: A tuple containing the new size and optionally the scale factor if return_scale is True.
  446. """
  447. w, h = old_size
  448. if isinstance(scale, (float, int)):
  449. if scale <= 0:
  450. raise ValueError(f"Invalid scale {scale}, must be positive.")
  451. scale_factor = scale
  452. elif isinstance(scale, list):
  453. max_long_edge = max(scale)
  454. max_short_edge = min(scale)
  455. scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w))
  456. else:
  457. raise TypeError(
  458. f"Scale must be a number or list of int, but got {type(scale)}"
  459. )
  460. def _scale_size(size, scale):
  461. if isinstance(scale, (float, int)):
  462. scale = (scale, scale)
  463. w, h = size
  464. return int(w * float(scale[0]) + 0.5), int(h * float(scale[1]) + 0.5)
  465. new_size = _scale_size((w, h), scale_factor)
  466. if return_scale:
  467. return new_size, scale_factor
  468. else:
  469. return new_size
  470. def imrescale(
  471. self, img, scale, return_scale=False, interpolation="bilinear", backend=None
  472. ):
  473. """Resize image while keeping the aspect ratio.
  474. Args:
  475. img (numpy.ndarray): The input image.
  476. scale (float): The scaling factor.
  477. return_scale (bool): Whether to return the scaling factor along with the resized image.
  478. interpolation (str): The interpolation method to use. Defaults to 'bilinear'.
  479. backend (str): The backend to use for resizing. Defaults to None.
  480. Returns:
  481. tuple or numpy.ndarray: The resized image, and optionally the scaling factor.
  482. """
  483. h, w = img.shape[:2]
  484. new_size, scale_factor = self.rescale_size((w, h), scale, return_scale=True)
  485. rescaled_img = self.imresize(
  486. img, new_size, interpolation=interpolation, backend=backend
  487. )
  488. if return_scale:
  489. return rescaled_img, scale_factor
  490. else:
  491. return rescaled_img
  492. def imresize(
  493. self,
  494. img,
  495. size,
  496. return_scale=False,
  497. interpolation="bilinear",
  498. out=None,
  499. backend=None,
  500. ):
  501. """Resize an image to a given size.
  502. Args:
  503. img (numpy.ndarray): The input image to be resized.
  504. size (tuple): The new size for the image as (height, width).
  505. return_scale (bool): Whether to return the scaling factors along with the resized image.
  506. interpolation (str): The interpolation method to use. Default is 'bilinear'.
  507. out (numpy.ndarray, optional): Output array. If provided, it must have the same shape and dtype as the output array.
  508. backend (str, optional): The backend to use for resizing. Supported backends are 'cv2' and 'pillow'.
  509. Returns:
  510. 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).
  511. """
  512. h, w = img.shape[:2]
  513. if backend not in ["cv2", "pillow"]:
  514. raise ValueError(
  515. f"backend: {backend} is not supported for resize."
  516. f"Supported backends are 'cv2', 'pillow'"
  517. )
  518. if backend == "pillow":
  519. raise NotImplementedError
  520. else:
  521. resized_img = cv2.resize(
  522. img, size, dst=out, interpolation=cv2_interp_codes[interpolation]
  523. )
  524. if not return_scale:
  525. return resized_img
  526. else:
  527. w_scale = size[0] / w
  528. h_scale = size[1] / h
  529. return resized_img, w_scale, h_scale
  530. def _resize_bboxes(self, results):
  531. """Resize bounding boxes with `results['scale_factor']`.
  532. Args:
  533. results (dict): A dictionary containing the bounding boxes and other related information.
  534. """
  535. for key in results.get("bbox_fields", []):
  536. bboxes = results[key] * results["scale_factor"]
  537. if self.bbox_clip_border:
  538. img_shape = results["img_shape"]
  539. bboxes[:, 0::2] = np.clip(bboxes[:, 0::2], 0, img_shape[1])
  540. bboxes[:, 1::2] = np.clip(bboxes[:, 1::2], 0, img_shape[0])
  541. results[key] = bboxes
  542. def _resize_masks(self, results):
  543. """Resize masks with ``results['scale']``"""
  544. raise NotImplementedError
  545. def _resize_seg(self, results):
  546. """Resize semantic segmentation map with ``results['scale']``."""
  547. raise NotImplementedError
  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. @benchmark.timeit
  579. class NormalizeImage:
  580. """Normalize the image."""
  581. """Normalize an image by subtracting the mean and dividing by the standard deviation.
  582. Args:
  583. mean (list or tuple): Mean values for each channel.
  584. std (list or tuple): Standard deviation values for each channel.
  585. to_rgb (bool): Whether to convert the image from BGR to RGB.
  586. """
  587. def __init__(self, mean, std, to_rgb=True):
  588. """Initializes the NormalizeImage class with mean, std, and to_rgb parameters."""
  589. self.mean = np.array(mean, dtype=np.float32)
  590. self.std = np.array(std, dtype=np.float32)
  591. self.to_rgb = to_rgb
  592. def _imnormalize(self, img, mean, std, to_rgb=True):
  593. """Normalize the given image inplace.
  594. Args:
  595. img (numpy.ndarray): The image to normalize.
  596. mean (numpy.ndarray): Mean values for normalization.
  597. std (numpy.ndarray): Standard deviation values for normalization.
  598. to_rgb (bool): Whether to convert the image from BGR to RGB.
  599. Returns:
  600. numpy.ndarray: The normalized image.
  601. """
  602. img = img.copy().astype(np.float32)
  603. mean = np.float64(mean.reshape(1, -1))
  604. stdinv = 1 / np.float64(std.reshape(1, -1))
  605. if to_rgb:
  606. cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img) # inplace
  607. cv2.subtract(img, mean, img) # inplace
  608. cv2.multiply(img, stdinv, img) # inplace
  609. return img
  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. @benchmark.timeit
  627. class PadImage(object):
  628. """Pad the image & mask."""
  629. def __init__(self, size=None, size_divisor=None, pad_val=0):
  630. self.size = size
  631. self.size_divisor = size_divisor
  632. self.pad_val = pad_val
  633. # only one of size and size_divisor should be valid
  634. assert size is not None or size_divisor is not None
  635. assert size is None or size_divisor is None
  636. def impad(
  637. self, img, *, shape=None, padding=None, pad_val=0, padding_mode="constant"
  638. ):
  639. """Pad the given image to a certain shape or pad on all sides
  640. Args:
  641. img (numpy.ndarray): The input image to be padded.
  642. shape (tuple, optional): Desired output shape in the form (height, width). One of shape or padding must be specified.
  643. padding (int, tuple, optional): Number of pixels to pad on each side of the image. If a single int is provided this
  644. 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).
  645. If a tuple of length 4 is provided this is interpreted as (top, right, bottom, left).
  646. pad_val (int, list, optional): Pixel value used for padding. If a list is provided, it must have the same length as the
  647. last dimension of the input image. Defaults to 0.
  648. padding_mode (str, optional): Padding mode to use. One of 'constant', 'edge', 'reflect', 'symmetric'.
  649. Defaults to 'constant'.
  650. Returns:
  651. numpy.ndarray: The padded image.
  652. """
  653. assert (shape is not None) ^ (padding is not None)
  654. if shape is not None:
  655. padding = [0, 0, shape[1] - img.shape[1], shape[0] - img.shape[0]]
  656. # check pad_val
  657. if isinstance(pad_val, list):
  658. assert len(pad_val) == img.shape[-1]
  659. elif not isinstance(pad_val, numbers.Number):
  660. raise TypeError(
  661. "pad_val must be a int or a list. " f"But received {type(pad_val)}"
  662. )
  663. # check padding
  664. if isinstance(padding, list) and len(padding) in [2, 4]:
  665. if len(padding) == 2:
  666. padding = [padding[0], padding[1], padding[0], padding[1]]
  667. elif isinstance(padding, numbers.Number):
  668. padding = [padding, padding, padding, padding]
  669. else:
  670. raise ValueError(
  671. "Padding must be a int or a 2, or 4 element list."
  672. f"But received {padding}"
  673. )
  674. # check padding mode
  675. assert padding_mode in ["constant", "edge", "reflect", "symmetric"]
  676. border_type = {
  677. "constant": cv2.BORDER_CONSTANT,
  678. "edge": cv2.BORDER_REPLICATE,
  679. "reflect": cv2.BORDER_REFLECT_101,
  680. "symmetric": cv2.BORDER_REFLECT,
  681. }
  682. img = cv2.copyMakeBorder(
  683. img,
  684. padding[1],
  685. padding[3],
  686. padding[0],
  687. padding[2],
  688. border_type[padding_mode],
  689. value=pad_val,
  690. )
  691. return img
  692. def impad_to_multiple(self, img, divisor, pad_val=0):
  693. """
  694. Pad an image to ensure each edge length is a multiple of a given number.
  695. Args:
  696. img (numpy.ndarray): The input image.
  697. divisor (int): The number to which each edge length should be a multiple.
  698. pad_val (int, optional): The value to pad the image with. Defaults to 0.
  699. Returns:
  700. numpy.ndarray: The padded image.
  701. """
  702. pad_h = int(np.ceil(img.shape[0] / divisor)) * divisor
  703. pad_w = int(np.ceil(img.shape[1] / divisor)) * divisor
  704. return self.impad(img, shape=(pad_h, pad_w), pad_val=pad_val)
  705. def _pad_img(self, results):
  706. """
  707. Pad images according to ``self.size`` or adjust their shapes to be multiples of ``self.size_divisor``.
  708. Args:
  709. results (dict): A dictionary containing image data, with 'img_fields' as an optional key
  710. pointing to a list of image field names.
  711. """
  712. for key in results.get("img_fields", ["img"]):
  713. if self.size is not None:
  714. padded_img = self.impad(
  715. results[key], shape=self.size, pad_val=self.pad_val
  716. )
  717. elif self.size_divisor is not None:
  718. for idx in range(len(results[key])):
  719. padded_img = self.impad_to_multiple(
  720. results[key][idx], self.size_divisor, pad_val=self.pad_val
  721. )
  722. results[key][idx] = padded_img
  723. results["pad_shape"] = padded_img.shape
  724. results["pad_fixed_size"] = self.size
  725. results["pad_size_divisor"] = self.size_divisor
  726. def _pad_masks(self, results):
  727. """Pad masks according to ``results['pad_shape']``."""
  728. raise NotImplementedError
  729. def _pad_seg(self, results):
  730. """Pad semantic segmentation map according to ``results['pad_shape']``."""
  731. raise NotImplementedError
  732. def __call__(self, results):
  733. """Call function to pad images, masks, semantic segmentation maps."""
  734. self._pad_img(results)
  735. return results
  736. @benchmark.timeit
  737. class SampleFilterByKey:
  738. """Collect data from the loader relevant to the specific task."""
  739. def __init__(
  740. self,
  741. keys,
  742. meta_keys=(
  743. "filename",
  744. "ori_shape",
  745. "img_shape",
  746. "lidar2img",
  747. "depth2img",
  748. "cam2img",
  749. "pad_shape",
  750. "scale_factor",
  751. "flip",
  752. "pcd_horizontal_flip",
  753. "pcd_vertical_flip",
  754. "box_type_3d",
  755. "img_norm_cfg",
  756. "pcd_trans",
  757. "sample_idx",
  758. "pcd_scale_factor",
  759. "pcd_rotation",
  760. "pts_filename",
  761. "transformation_3d_flow",
  762. ),
  763. ):
  764. self.keys = keys
  765. self.meta_keys = meta_keys
  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. @benchmark.timeit
  784. class GetInferInput:
  785. """Collect infer input data from transformed sample"""
  786. def collate_fn(self, batch):
  787. sample = batch[0]
  788. collated_batch = {}
  789. collated_fields = [
  790. "img",
  791. "points",
  792. "img_metas",
  793. "gt_bboxes_3d",
  794. "gt_labels_3d",
  795. "modality",
  796. "meta",
  797. "idx",
  798. "img_depth",
  799. ]
  800. for k in list(sample.keys()):
  801. if k not in collated_fields:
  802. continue
  803. if k == "img":
  804. collated_batch[k] = np.stack([elem[k] for elem in batch], axis=0)
  805. elif k == "img_depth":
  806. collated_batch[k] = np.stack(
  807. [np.stack(elem[k], axis=0) for elem in batch], axis=0
  808. )
  809. else:
  810. collated_batch[k] = [elem[k] for elem in batch]
  811. return collated_batch
  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