functional.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. """Functional implementations of image cropping operations.
  2. This module provides utility functions for performing various cropping operations on images,
  3. bounding boxes, and keypoints. It includes functions to calculate crop coordinates, crop images,
  4. and handle the corresponding transformations for bounding boxes and keypoints to maintain
  5. consistency between different data types during cropping operations.
  6. """
  7. from __future__ import annotations
  8. from collections.abc import Sequence
  9. from typing import Any
  10. import cv2
  11. import numpy as np
  12. from albucore import maybe_process_in_chunks, preserve_channel_dim
  13. from albumentations.augmentations.geometric import functional as fgeometric
  14. from albumentations.augmentations.utils import handle_empty_array
  15. from albumentations.core.bbox_utils import denormalize_bboxes, normalize_bboxes
  16. __all__ = [
  17. "crop",
  18. "crop_and_pad",
  19. "crop_and_pad_bboxes",
  20. "crop_and_pad_keypoints",
  21. "crop_bboxes_by_coords",
  22. "crop_keypoints_by_coords",
  23. "get_center_crop_coords",
  24. "get_crop_coords",
  25. "pad_along_axes",
  26. "volume_crop_yx",
  27. "volumes_crop_yx",
  28. ]
  29. def get_crop_coords(
  30. image_shape: tuple[int, int],
  31. crop_shape: tuple[int, int],
  32. h_start: float,
  33. w_start: float,
  34. ) -> tuple[int, int, int, int]:
  35. """Get crop coordinates.
  36. This function gets the crop coordinates.
  37. Args:
  38. image_shape (tuple[int, int]): Original image shape.
  39. crop_shape (tuple[int, int]): Crop shape.
  40. h_start (float): Start height.
  41. w_start (float): Start width.
  42. Returns:
  43. tuple[int, int, int, int]: Crop coordinates.
  44. """
  45. # h_start is [0, 1) and should map to [0, (height - crop_height)] (note inclusive)
  46. # This is conceptually equivalent to mapping onto `range(0, (height - crop_height + 1))`
  47. # See: https://github.com/albumentations-team/albumentations/pull/1080
  48. # We want range for coordinated to be [0, image_size], right side is included
  49. height, width = image_shape[:2]
  50. # Clip crop dimensions to image dimensions
  51. crop_height = min(crop_shape[0], height)
  52. crop_width = min(crop_shape[1], width)
  53. y_min = int((height - crop_height + 1) * h_start)
  54. y_max = y_min + crop_height
  55. x_min = int((width - crop_width + 1) * w_start)
  56. x_max = x_min + crop_width
  57. return x_min, y_min, x_max, y_max
  58. def crop_bboxes_by_coords(
  59. bboxes: np.ndarray,
  60. crop_coords: tuple[int, int, int, int],
  61. image_shape: tuple[int, int],
  62. normalized_input: bool = True,
  63. ) -> np.ndarray:
  64. """Crop bounding boxes based on given crop coordinates.
  65. This function adjusts bounding boxes to fit within a cropped image.
  66. Args:
  67. bboxes (np.ndarray): Array of bounding boxes with shape (N, 4+) where each row is
  68. [x_min, y_min, x_max, y_max, ...]. The bounding box coordinates
  69. can be either normalized (in [0, 1]) if normalized_input=True or
  70. absolute pixel values if normalized_input=False.
  71. crop_coords (tuple[int, int, int, int]): Crop coordinates (x_min, y_min, x_max, y_max)
  72. in absolute pixel values.
  73. image_shape (tuple[int, int]): Original image shape (height, width).
  74. normalized_input (bool): Whether input boxes are in normalized coordinates.
  75. If True, assumes input is normalized [0,1] and returns normalized coordinates.
  76. If False, assumes input is in absolute pixels and returns absolute coordinates.
  77. Default: True for backward compatibility.
  78. Returns:
  79. np.ndarray: Array of cropped bounding boxes. Coordinates will be in the same format as input
  80. (normalized if normalized_input=True, absolute pixels if normalized_input=False).
  81. Note:
  82. Bounding boxes that fall completely outside the crop area will be removed.
  83. Bounding boxes that partially overlap with the crop area will be adjusted to fit within it.
  84. """
  85. if not bboxes.size:
  86. return bboxes
  87. # Convert to absolute coordinates if needed
  88. if normalized_input:
  89. cropped_bboxes = denormalize_bboxes(bboxes.copy().astype(np.float32), image_shape)
  90. else:
  91. cropped_bboxes = bboxes.copy().astype(np.float32)
  92. x_min, y_min = crop_coords[:2]
  93. # Subtract crop coordinates
  94. cropped_bboxes[:, [0, 2]] -= x_min
  95. cropped_bboxes[:, [1, 3]] -= y_min
  96. # Calculate crop shape
  97. crop_height = crop_coords[3] - crop_coords[1]
  98. crop_width = crop_coords[2] - crop_coords[0]
  99. crop_shape = (crop_height, crop_width)
  100. # Return in same format as input
  101. return normalize_bboxes(cropped_bboxes, crop_shape) if normalized_input else cropped_bboxes
  102. @handle_empty_array("keypoints")
  103. def crop_keypoints_by_coords(
  104. keypoints: np.ndarray,
  105. crop_coords: tuple[int, int, int, int],
  106. ) -> np.ndarray:
  107. """Crop keypoints using the provided coordinates of bottom-left and top-right corners in pixels.
  108. Args:
  109. keypoints (np.ndarray): An array of keypoints with shape (N, 4+) where each row is (x, y, angle, scale, ...).
  110. crop_coords (tuple): Crop box coords (x1, y1, x2, y2).
  111. Returns:
  112. np.ndarray: An array of cropped keypoints with the same shape as the input.
  113. """
  114. x1, y1 = crop_coords[:2]
  115. cropped_keypoints = keypoints.copy()
  116. cropped_keypoints[:, 0] -= x1 # Adjust x coordinates
  117. cropped_keypoints[:, 1] -= y1 # Adjust y coordinates
  118. return cropped_keypoints
  119. def get_center_crop_coords(image_shape: tuple[int, int], crop_shape: tuple[int, int]) -> tuple[int, int, int, int]:
  120. """Get center crop coordinates.
  121. This function gets the center crop coordinates.
  122. Args:
  123. image_shape (tuple[int, int]): Original image shape.
  124. crop_shape (tuple[int, int]): Crop shape.
  125. Returns:
  126. tuple[int, int, int, int]: Center crop coordinates.
  127. """
  128. height, width = image_shape[:2]
  129. crop_height, crop_width = crop_shape[:2]
  130. y_min = (height - crop_height) // 2
  131. y_max = y_min + crop_height
  132. x_min = (width - crop_width) // 2
  133. x_max = x_min + crop_width
  134. return x_min, y_min, x_max, y_max
  135. def crop(img: np.ndarray, x_min: int, y_min: int, x_max: int, y_max: int) -> np.ndarray:
  136. """Crop an image.
  137. This function crops an image.
  138. Args:
  139. img (np.ndarray): Input image.
  140. x_min (int): Minimum x coordinate.
  141. y_min (int): Minimum y coordinate.
  142. x_max (int): Maximum x coordinate.
  143. y_max (int): Maximum y coordinate.
  144. Returns:
  145. np.ndarray: Cropped image.
  146. """
  147. height, width = img.shape[:2]
  148. if x_max <= x_min or y_max <= y_min:
  149. raise ValueError(
  150. "We should have x_min < x_max and y_min < y_max. But we got"
  151. f" (x_min = {x_min}, y_min = {y_min}, x_max = {x_max}, y_max = {y_max})",
  152. )
  153. if x_min < 0 or x_max > width or y_min < 0 or y_max > height:
  154. raise ValueError(
  155. "Values for crop should be non negative and equal or smaller than image sizes"
  156. f"(x_min = {x_min}, y_min = {y_min}, x_max = {x_max}, y_max = {y_max}, "
  157. f"height = {height}, width = {width})",
  158. )
  159. return img[y_min:y_max, x_min:x_max]
  160. @preserve_channel_dim
  161. def crop_and_pad(
  162. img: np.ndarray,
  163. crop_params: tuple[int, int, int, int] | None,
  164. pad_params: tuple[int, int, int, int] | None,
  165. pad_value: tuple[float, ...] | float | None,
  166. image_shape: tuple[int, int],
  167. interpolation: int,
  168. pad_mode: int,
  169. keep_size: bool,
  170. ) -> np.ndarray:
  171. """Crop and pad an image.
  172. This function crops and pads an image.
  173. Args:
  174. img (np.ndarray): Input image.
  175. crop_params (tuple[int, int, int, int] | None): Crop parameters.
  176. pad_params (tuple[int, int, int, int] | None): Pad parameters.
  177. pad_value (tuple[float, ...] | float | None): Pad value.
  178. image_shape (tuple[int, int]): Original image shape.
  179. interpolation (int): Interpolation method.
  180. pad_mode (int): Pad mode.
  181. keep_size (bool): Whether to keep the original size.
  182. Returns:
  183. np.ndarray: Cropped and padded image.
  184. """
  185. if crop_params is not None and any(i != 0 for i in crop_params):
  186. img = crop(img, *crop_params)
  187. if pad_params is not None and any(i != 0 for i in pad_params):
  188. img = fgeometric.pad_with_params(
  189. img,
  190. pad_params[0],
  191. pad_params[1],
  192. pad_params[2],
  193. pad_params[3],
  194. border_mode=pad_mode,
  195. value=pad_value,
  196. )
  197. if keep_size:
  198. rows, cols = image_shape[:2]
  199. resize_fn = maybe_process_in_chunks(cv2.resize, dsize=(cols, rows), interpolation=interpolation)
  200. return resize_fn(img)
  201. return img
  202. def crop_and_pad_bboxes(
  203. bboxes: np.ndarray,
  204. crop_params: tuple[int, int, int, int] | None,
  205. pad_params: tuple[int, int, int, int] | None,
  206. image_shape: tuple[int, int],
  207. result_shape: tuple[int, int],
  208. ) -> np.ndarray:
  209. """Crop and pad bounding boxes.
  210. This function crops and pads bounding boxes.
  211. Args:
  212. bboxes (np.ndarray): Array of bounding boxes.
  213. crop_params (tuple[int, int, int, int] | None): Crop parameters.
  214. pad_params (tuple[int, int, int, int] | None): Pad parameters.
  215. image_shape (tuple[int, int]): Original image shape.
  216. result_shape (tuple[int, int]): Result image shape.
  217. Returns:
  218. np.ndarray: Array of cropped and padded bounding boxes.
  219. """
  220. if len(bboxes) == 0:
  221. return bboxes
  222. # Denormalize bboxes
  223. denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
  224. if crop_params is not None:
  225. crop_x, crop_y = crop_params[:2]
  226. # Subtract crop values from x and y coordinates
  227. denormalized_bboxes[:, [0, 2]] -= crop_x
  228. denormalized_bboxes[:, [1, 3]] -= crop_y
  229. if pad_params is not None:
  230. top, _, left, _ = pad_params
  231. # Add pad values to x and y coordinates
  232. denormalized_bboxes[:, [0, 2]] += left
  233. denormalized_bboxes[:, [1, 3]] += top
  234. # Normalize bboxes to the result shape
  235. return normalize_bboxes(denormalized_bboxes, result_shape)
  236. @handle_empty_array("keypoints")
  237. def crop_and_pad_keypoints(
  238. keypoints: np.ndarray,
  239. crop_params: tuple[int, int, int, int] | None = None,
  240. pad_params: tuple[int, int, int, int] | None = None,
  241. image_shape: tuple[int, int] = (0, 0),
  242. result_shape: tuple[int, int] = (0, 0),
  243. keep_size: bool = False,
  244. ) -> np.ndarray:
  245. """Crop and pad multiple keypoints simultaneously.
  246. Args:
  247. keypoints (np.ndarray): Array of keypoints with shape (N, 4+) where each row is (x, y, angle, scale, ...).
  248. crop_params (Sequence[int], optional): Crop parameters [crop_x1, crop_y1, ...].
  249. pad_params (Sequence[int], optional): Pad parameters [top, bottom, left, right].
  250. image_shape (Tuple[int, int]): Original image shape (rows, cols).
  251. result_shape (Tuple[int, int]): Result image shape (rows, cols).
  252. keep_size (bool): Whether to keep the original size.
  253. Returns:
  254. np.ndarray: Array of transformed keypoints with the same shape as input.
  255. """
  256. transformed_keypoints = keypoints.copy()
  257. if crop_params is not None:
  258. crop_x1, crop_y1 = crop_params[:2]
  259. transformed_keypoints[:, 0] -= crop_x1
  260. transformed_keypoints[:, 1] -= crop_y1
  261. if pad_params is not None:
  262. top, _, left, _ = pad_params
  263. transformed_keypoints[:, 0] += left
  264. transformed_keypoints[:, 1] += top
  265. rows, cols = image_shape[:2]
  266. result_rows, result_cols = result_shape[:2]
  267. if keep_size and (result_cols != cols or result_rows != rows):
  268. scale_x = cols / result_cols
  269. scale_y = rows / result_rows
  270. return fgeometric.keypoints_scale(transformed_keypoints, scale_x, scale_y)
  271. return transformed_keypoints
  272. def volume_crop_yx(
  273. volume: np.ndarray,
  274. x_min: int,
  275. y_min: int,
  276. x_max: int,
  277. y_max: int,
  278. ) -> np.ndarray:
  279. """Crop a single volume along Y (height) and X (width) axes only.
  280. Args:
  281. volume (np.ndarray): Input volume with shape (D, H, W) or (D, H, W, C).
  282. x_min (int): Minimum width coordinate.
  283. y_min (int): Minimum height coordinate.
  284. x_max (int): Maximum width coordinate.
  285. y_max (int): Maximum height coordinate.
  286. Returns:
  287. np.ndarray: Cropped volume (D, H_new, W_new, [C]).
  288. Raises:
  289. ValueError: If crop coordinates are invalid.
  290. """
  291. _, height, width = volume.shape[:3]
  292. if x_max <= x_min or y_max <= y_min:
  293. raise ValueError(
  294. "Crop coordinates must satisfy min < max. Got: "
  295. f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max})",
  296. )
  297. if x_min < 0 or y_min < 0 or x_max > width or y_max > height:
  298. raise ValueError(
  299. "Crop coordinates must be within image dimensions (H, W). Got: "
  300. f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max}) "
  301. f"for volume shape {volume.shape[:3]}",
  302. )
  303. # Crop along H (axis 1) and W (axis 2)
  304. return volume[:, y_min:y_max, x_min:x_max]
  305. def volumes_crop_yx(
  306. volumes: np.ndarray,
  307. x_min: int,
  308. y_min: int,
  309. x_max: int,
  310. y_max: int,
  311. ) -> np.ndarray:
  312. """Crop a batch of volumes along Y (height) and X (width) axes only.
  313. Args:
  314. volumes (np.ndarray): Input batch of volumes with shape (B, D, H, W) or (B, D, H, W, C).
  315. x_min (int): Minimum width coordinate.
  316. y_min (int): Minimum height coordinate.
  317. x_max (int): Maximum width coordinate.
  318. y_max (int): Maximum height coordinate.
  319. Returns:
  320. np.ndarray: Cropped batch of volumes (B, D, H_new, W_new, [C]).
  321. Raises:
  322. ValueError: If crop coordinates are invalid or volumes shape is incorrect.
  323. """
  324. if not 4 <= volumes.ndim <= 5:
  325. raise ValueError(f"Input volumes should have 4 or 5 dimensions, got {volumes.ndim}")
  326. depth, height, width = volumes.shape[1:4]
  327. if x_max <= x_min or y_max <= y_min:
  328. raise ValueError(
  329. "Crop coordinates must satisfy min < max. Got: "
  330. f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max})",
  331. )
  332. if x_min < 0 or y_min < 0 or x_max > width or y_max > height:
  333. raise ValueError(
  334. "Crop coordinates must be within image dimensions (H, W). Got: "
  335. f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max}) "
  336. f"for volume shape {(depth, height, width)}",
  337. )
  338. # Crop along H (axis 2) and W (axis 3)
  339. return volumes[:, :, y_min:y_max, x_min:x_max]
  340. def pad_along_axes(
  341. arr: np.ndarray,
  342. pad_top: int,
  343. pad_bottom: int,
  344. pad_left: int,
  345. pad_right: int,
  346. h_axis: int,
  347. w_axis: int,
  348. border_mode: int,
  349. pad_value: float | Sequence[float] = 0,
  350. ) -> np.ndarray:
  351. """Pad an array along specified height (H) and width (W) axes using np.pad.
  352. Args:
  353. arr (np.ndarray): Input array.
  354. pad_top (int): Padding added to the top (start of H axis).
  355. pad_bottom (int): Padding added to the bottom (end of H axis).
  356. pad_left (int): Padding added to the left (start of W axis).
  357. pad_right (int): Padding added to the right (end of W axis).
  358. h_axis (int): Index of the height axis (Y).
  359. w_axis (int): Index of the width axis (X).
  360. border_mode (int): OpenCV border mode.
  361. pad_value (float | Sequence[float]): Value for constant padding.
  362. Returns:
  363. np.ndarray: Padded array.
  364. Raises:
  365. ValueError: If border_mode is unsupported or axis indices are out of bounds.
  366. """
  367. ndim = arr.ndim
  368. if not (0 <= h_axis < ndim and 0 <= w_axis < ndim):
  369. raise ValueError(f"Axis indices {h_axis}, {w_axis} are out of bounds for array with {ndim} dimensions.")
  370. if h_axis == w_axis:
  371. raise ValueError(f"Height axis {h_axis} and width axis {w_axis} cannot be the same.")
  372. mode_map = {
  373. cv2.BORDER_CONSTANT: "constant",
  374. cv2.BORDER_REPLICATE: "edge",
  375. cv2.BORDER_REFLECT: "reflect",
  376. cv2.BORDER_REFLECT_101: "symmetric",
  377. cv2.BORDER_WRAP: "wrap",
  378. }
  379. if border_mode not in mode_map:
  380. raise ValueError(f"Unsupported border_mode: {border_mode}")
  381. np_mode = mode_map[border_mode]
  382. pad_width = [(0, 0)] * ndim # Initialize padding for all dimensions
  383. pad_width[h_axis] = (pad_top, pad_bottom)
  384. pad_width[w_axis] = (pad_left, pad_right)
  385. # Initialize kwargs with mode
  386. kwargs: dict[str, Any] = {"mode": np_mode}
  387. # Add constant_values only if mode is constant
  388. if np_mode == "constant":
  389. kwargs["constant_values"] = pad_value
  390. return np.pad(arr, pad_width, **kwargs)