processors.py 36 KB

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