distortion.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. """Geometric distortion transforms for image augmentation.
  2. This module provides various geometric distortion transformations that modify the spatial arrangement
  3. of pixels in images while preserving their intensity values. These transforms can create
  4. non-rigid deformations that are useful for data augmentation, especially when training models
  5. that need to be robust to geometric variations.
  6. Available transforms:
  7. - ElasticTransform: Creates random elastic deformations by displacing pixels along random vectors
  8. - GridDistortion: Distorts the image by moving the nodes of a grid placed on the image
  9. - OpticalDistortion: Simulates lens distortion effects (barrel/pincushion) using camera or fisheye models
  10. - PiecewiseAffine: Divides the image into a grid and applies random affine transformations to each cell
  11. - ThinPlateSpline: Applies smooth deformations based on the thin plate spline interpolation technique
  12. All transforms inherit from BaseDistortion, which provides a common interface and functionality
  13. for applying distortion maps to various target types (images, masks, bounding boxes, keypoints).
  14. These transforms are particularly useful for:
  15. - Data augmentation to increase training set diversity
  16. - Simulating real-world distortion effects like camera lens aberrations
  17. - Creating more challenging test cases for computer vision models
  18. - Medical image analysis where anatomy might appear in different shapes
  19. Each transform supports customization through various parameters controlling the strength,
  20. type, and characteristics of the distortion, as well as interpolation methods for different
  21. target types.
  22. """
  23. from __future__ import annotations
  24. from typing import Annotated, Any, Literal, cast
  25. from warnings import warn
  26. import cv2
  27. import numpy as np
  28. from albucore import batch_transform
  29. from pydantic import (
  30. AfterValidator,
  31. Field,
  32. ValidationInfo,
  33. field_validator,
  34. )
  35. from albumentations.augmentations.utils import check_range
  36. from albumentations.core.bbox_utils import (
  37. denormalize_bboxes,
  38. normalize_bboxes,
  39. )
  40. from albumentations.core.pydantic import (
  41. NonNegativeFloatRangeType,
  42. SymmetricRangeType,
  43. check_range_bounds,
  44. )
  45. from albumentations.core.transforms_interface import (
  46. BaseTransformInitSchema,
  47. DualTransform,
  48. )
  49. from albumentations.core.type_definitions import (
  50. ALL_TARGETS,
  51. BIG_INTEGER,
  52. )
  53. from albumentations.core.utils import to_tuple
  54. from . import functional as fgeometric
  55. __all__ = [
  56. "ElasticTransform",
  57. "GridDistortion",
  58. "OpticalDistortion",
  59. "PiecewiseAffine",
  60. "ThinPlateSpline",
  61. ]
  62. class BaseDistortion(DualTransform):
  63. """Base class for distortion-based transformations.
  64. This class provides a foundation for implementing various types of image distortions,
  65. such as optical distortions, grid distortions, and elastic transformations. It handles
  66. the common operations of applying distortions to images, masks, bounding boxes, and keypoints.
  67. Args:
  68. interpolation (int): Interpolation method to be used for image transformation.
  69. Should be one of the OpenCV interpolation types (e.g., cv2.INTER_LINEAR,
  70. cv2.INTER_CUBIC).
  71. mask_interpolation (int): Flag that is used to specify the interpolation algorithm for mask.
  72. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
  73. keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
  74. - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
  75. less accurate for large distortions. Recommended for large images or many keypoints.
  76. - "direct": Uses inverse mapping. More accurate for large distortions but slower.
  77. Default: "mask"
  78. p (float): Probability of applying the transform.
  79. Targets:
  80. image, mask, bboxes, keypoints, volume, mask3d
  81. Image types:
  82. uint8, float32
  83. Note:
  84. - This is an abstract base class and should not be used directly.
  85. - Subclasses should implement the `get_params_dependent_on_data` method to generate
  86. the distortion maps (map_x and map_y).
  87. - The distortion is applied consistently across all targets (image, mask, bboxes, keypoints)
  88. to maintain coherence in the augmented data.
  89. Examples:
  90. >>> import numpy as np
  91. >>> import albumentations as A
  92. >>> import cv2
  93. >>>
  94. >>> class CustomDistortion(A.BaseDistortion):
  95. ... def __init__(self, distort_limit=0.3, *args, **kwargs):
  96. ... super().__init__(*args, **kwargs)
  97. ... self.distort_limit = distort_limit
  98. ...
  99. ... def get_params_dependent_on_data(self, params, data):
  100. ... height, width = params["shape"][:2]
  101. ... # Create distortion maps - a simple radial distortion in this example
  102. ... map_x = np.zeros((height, width), dtype=np.float32)
  103. ... map_y = np.zeros((height, width), dtype=np.float32)
  104. ...
  105. ... # Calculate distortion center
  106. ... center_x = width / 2
  107. ... center_y = height / 2
  108. ...
  109. ... # Generate distortion maps
  110. ... for y in range(height):
  111. ... for x in range(width):
  112. ... # Distance from center
  113. ... dx = (x - center_x) / width
  114. ... dy = (y - center_y) / height
  115. ... r = np.sqrt(dx * dx + dy * dy)
  116. ...
  117. ... # Apply radial distortion
  118. ... factor = 1 + self.distort_limit * r
  119. ... map_x[y, x] = x + dx * factor
  120. ... map_y[y, x] = y + dy * factor
  121. ...
  122. ... return {"map_x": map_x, "map_y": map_y}
  123. >>>
  124. >>> # Prepare sample data
  125. >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
  126. >>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
  127. >>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
  128. >>> bbox_labels = [1, 2]
  129. >>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
  130. >>> keypoint_labels = [0, 1]
  131. >>>
  132. >>> # Define transform with the custom distortion
  133. >>> transform = A.Compose([
  134. ... CustomDistortion(
  135. ... distort_limit=0.2,
  136. ... interpolation=cv2.INTER_LINEAR,
  137. ... mask_interpolation=cv2.INTER_NEAREST,
  138. ... keypoint_remapping_method="mask",
  139. ... p=1.0
  140. ... )
  141. ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
  142. ... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
  143. >>>
  144. >>> # Apply the transform
  145. >>> transformed = transform(
  146. ... image=image,
  147. ... mask=mask,
  148. ... bboxes=bboxes,
  149. ... bbox_labels=bbox_labels,
  150. ... keypoints=keypoints,
  151. ... keypoint_labels=keypoint_labels
  152. ... )
  153. >>>
  154. >>> # Get the transformed data
  155. >>> transformed_image = transformed['image']
  156. >>> transformed_mask = transformed['mask']
  157. >>> transformed_bboxes = transformed['bboxes']
  158. >>> transformed_keypoints = transformed['keypoints']
  159. """
  160. _targets = ALL_TARGETS
  161. class InitSchema(BaseTransformInitSchema):
  162. interpolation: Literal[cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
  163. mask_interpolation: Literal[
  164. cv2.INTER_NEAREST,
  165. cv2.INTER_LINEAR,
  166. cv2.INTER_CUBIC,
  167. cv2.INTER_AREA,
  168. cv2.INTER_LANCZOS4,
  169. ]
  170. keypoint_remapping_method: Literal["direct", "mask"]
  171. border_mode: Literal[
  172. cv2.BORDER_CONSTANT,
  173. cv2.BORDER_REPLICATE,
  174. cv2.BORDER_REFLECT,
  175. cv2.BORDER_WRAP,
  176. cv2.BORDER_REFLECT_101,
  177. ]
  178. fill: tuple[float, ...] | float
  179. fill_mask: tuple[float, ...] | float
  180. def __init__(
  181. self,
  182. interpolation: Literal[
  183. cv2.INTER_NEAREST,
  184. cv2.INTER_LINEAR,
  185. cv2.INTER_CUBIC,
  186. cv2.INTER_AREA,
  187. cv2.INTER_LANCZOS4,
  188. ],
  189. mask_interpolation: Literal[
  190. cv2.INTER_NEAREST,
  191. cv2.INTER_LINEAR,
  192. cv2.INTER_CUBIC,
  193. cv2.INTER_AREA,
  194. cv2.INTER_LANCZOS4,
  195. ],
  196. keypoint_remapping_method: Literal["direct", "mask"],
  197. p: float,
  198. border_mode: Literal[
  199. cv2.BORDER_CONSTANT,
  200. cv2.BORDER_REPLICATE,
  201. cv2.BORDER_REFLECT,
  202. cv2.BORDER_WRAP,
  203. cv2.BORDER_REFLECT_101,
  204. ] = cv2.BORDER_CONSTANT,
  205. fill: tuple[float, ...] | float = 0,
  206. fill_mask: tuple[float, ...] | float = 0,
  207. ):
  208. super().__init__(p=p)
  209. self.interpolation = interpolation
  210. self.mask_interpolation = mask_interpolation
  211. self.keypoint_remapping_method = keypoint_remapping_method
  212. self.border_mode = border_mode
  213. self.fill = fill
  214. self.fill_mask = fill_mask
  215. def apply(
  216. self,
  217. img: np.ndarray,
  218. map_x: np.ndarray,
  219. map_y: np.ndarray,
  220. **params: Any,
  221. ) -> np.ndarray:
  222. """Apply the distortion to the input image.
  223. Args:
  224. img (np.ndarray): Input image to be distorted.
  225. map_x (np.ndarray): X-coordinate map of the distortion.
  226. map_y (np.ndarray): Y-coordinate map of the distortion.
  227. **params (Any): Additional parameters.
  228. Returns:
  229. np.ndarray: Distorted image.
  230. """
  231. return fgeometric.remap(
  232. img,
  233. map_x,
  234. map_y,
  235. self.interpolation,
  236. self.border_mode,
  237. self.fill,
  238. )
  239. @batch_transform("spatial", has_batch_dim=True, has_depth_dim=False)
  240. def apply_to_images(self, images: np.ndarray, **params: Any) -> np.ndarray:
  241. """Apply the distortion to a batch of images.
  242. Args:
  243. images (np.ndarray): Batch of images to be distorted.
  244. **params (Any): Additional parameters.
  245. Returns:
  246. np.ndarray: Batch of distorted images.
  247. """
  248. return self.apply(images, **params)
  249. @batch_transform("spatial", has_batch_dim=False, has_depth_dim=True)
  250. def apply_to_volume(self, volume: np.ndarray, **params: Any) -> np.ndarray:
  251. """Apply the distortion to a volume.
  252. Args:
  253. volume (np.ndarray): Volume to be distorted.
  254. **params (Any): Additional parameters.
  255. Returns:
  256. np.ndarray: Distorted volume.
  257. """
  258. return self.apply(volume, **params)
  259. @batch_transform("spatial", has_batch_dim=True, has_depth_dim=True)
  260. def apply_to_volumes(self, volumes: np.ndarray, **params: Any) -> np.ndarray:
  261. """Apply the distortion to a batch of volumes.
  262. Args:
  263. volumes (np.ndarray): Batch of volumes to be distorted.
  264. **params (Any): Additional parameters.
  265. Returns:
  266. np.ndarray: Batch of distorted volumes.
  267. """
  268. return self.apply(volumes, **params)
  269. @batch_transform("spatial", has_batch_dim=True, has_depth_dim=False)
  270. def apply_to_mask3d(self, mask3d: np.ndarray, **params: Any) -> np.ndarray:
  271. """Apply the distortion to a 3D mask.
  272. Args:
  273. mask3d (np.ndarray): 3D mask to be distorted.
  274. **params (Any): Additional parameters.
  275. Returns:
  276. np.ndarray: Distorted 3D mask.
  277. """
  278. return self.apply_to_mask(mask3d, **params)
  279. def apply_to_mask(
  280. self,
  281. mask: np.ndarray,
  282. map_x: np.ndarray,
  283. map_y: np.ndarray,
  284. **params: Any,
  285. ) -> np.ndarray:
  286. """Apply the distortion to a mask.
  287. Args:
  288. mask (np.ndarray): Mask to be distorted.
  289. map_x (np.ndarray): X-coordinate map of the distortion.
  290. map_y (np.ndarray): Y-coordinate map of the distortion.
  291. **params (Any): Additional parameters.
  292. Returns:
  293. np.ndarray: Distorted mask.
  294. """
  295. return fgeometric.remap(
  296. mask,
  297. map_x,
  298. map_y,
  299. self.mask_interpolation,
  300. self.border_mode,
  301. self.fill_mask,
  302. )
  303. def apply_to_bboxes(
  304. self,
  305. bboxes: np.ndarray,
  306. map_x: np.ndarray,
  307. map_y: np.ndarray,
  308. **params: Any,
  309. ) -> np.ndarray:
  310. """Apply the distortion to bounding boxes.
  311. Args:
  312. bboxes (np.ndarray): Bounding boxes to be distorted.
  313. map_x (np.ndarray): X-coordinate map of the distortion.
  314. map_y (np.ndarray): Y-coordinate map of the distortion.
  315. **params (Any): Additional parameters.
  316. Returns:
  317. np.ndarray: Distorted bounding boxes.
  318. """
  319. image_shape = params["shape"][:2]
  320. bboxes_denorm = denormalize_bboxes(bboxes, image_shape)
  321. bboxes_returned = fgeometric.remap_bboxes(
  322. bboxes_denorm,
  323. map_x,
  324. map_y,
  325. image_shape,
  326. )
  327. return normalize_bboxes(bboxes_returned, image_shape)
  328. def apply_to_keypoints(
  329. self,
  330. keypoints: np.ndarray,
  331. map_x: np.ndarray,
  332. map_y: np.ndarray,
  333. **params: Any,
  334. ) -> np.ndarray:
  335. """Apply the distortion to keypoints.
  336. Args:
  337. keypoints (np.ndarray): Keypoints to be distorted.
  338. map_x (np.ndarray): X-coordinate map of the distortion.
  339. map_y (np.ndarray): Y-coordinate map of the distortion.
  340. **params (Any): Additional parameters.
  341. Returns:
  342. np.ndarray: Distorted keypoints.
  343. """
  344. if self.keypoint_remapping_method == "direct":
  345. return fgeometric.remap_keypoints(keypoints, map_x, map_y, params["shape"])
  346. return fgeometric.remap_keypoints_via_mask(keypoints, map_x, map_y, params["shape"])
  347. class ElasticTransform(BaseDistortion):
  348. """Apply elastic deformation to images, masks, bounding boxes, and keypoints.
  349. This transformation introduces random elastic distortions to the input data. It's particularly
  350. useful for data augmentation in training deep learning models, especially for tasks like
  351. image segmentation or object detection where you want to maintain the relative positions of
  352. features while introducing realistic deformations.
  353. The transform works by generating random displacement fields and applying them to the input.
  354. These fields are smoothed using a Gaussian filter to create more natural-looking distortions.
  355. Args:
  356. alpha (float): Scaling factor for the random displacement fields. Higher values result in
  357. more pronounced distortions. Default: 1.0
  358. sigma (float): Standard deviation of the Gaussian filter used to smooth the displacement
  359. fields. Higher values result in smoother, more global distortions. Default: 50.0
  360. interpolation (int): Interpolation method to be used for image transformation. Should be one
  361. of the OpenCV interpolation types. Default: cv2.INTER_LINEAR
  362. approximate (bool): Whether to use an approximate version of the elastic transform. If True,
  363. uses a fixed kernel size for Gaussian smoothing, which can be faster but potentially
  364. less accurate for large sigma values. Default: False
  365. same_dxdy (bool): Whether to use the same random displacement field for both x and y
  366. directions. Can speed up the transform at the cost of less diverse distortions. Default: False
  367. mask_interpolation (int): Flag that is used to specify the interpolation algorithm for mask.
  368. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
  369. Default: cv2.INTER_NEAREST.
  370. noise_distribution (Literal["gaussian", "uniform"]): Distribution used to generate the displacement fields.
  371. "gaussian" generates fields using normal distribution (more natural deformations).
  372. "uniform" generates fields using uniform distribution (more mechanical deformations).
  373. Default: "gaussian".
  374. keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
  375. - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
  376. less accurate for large distortions. Recommended for large images or many keypoints.
  377. - "direct": Uses inverse mapping. More accurate for large distortions but slower.
  378. Default: "mask"
  379. p (float): Probability of applying the transform. Default: 0.5
  380. Targets:
  381. image, mask, bboxes, keypoints, volume, mask3d
  382. Image types:
  383. uint8, float32
  384. Note:
  385. - The transform will maintain consistency across all targets (image, mask, bboxes, keypoints)
  386. by using the same displacement fields for all.
  387. - The 'approximate' parameter determines whether to use a precise or approximate method for
  388. generating displacement fields. The approximate method can be faster but may be less
  389. accurate for large sigma values.
  390. - Bounding boxes that end up outside the image after transformation will be removed.
  391. - Keypoints that end up outside the image after transformation will be removed.
  392. Examples:
  393. >>> import albumentations as A
  394. >>> transform = A.Compose([
  395. ... A.ElasticTransform(alpha=1, sigma=50, p=0.5),
  396. ... ])
  397. >>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
  398. >>> transformed_image = transformed['image']
  399. >>> transformed_mask = transformed['mask']
  400. >>> transformed_bboxes = transformed['bboxes']
  401. >>> transformed_keypoints = transformed['keypoints']
  402. """
  403. class InitSchema(BaseDistortion.InitSchema):
  404. alpha: Annotated[float, Field(ge=0)]
  405. sigma: Annotated[float, Field(ge=1)]
  406. approximate: bool
  407. same_dxdy: bool
  408. noise_distribution: Literal["gaussian", "uniform"]
  409. keypoint_remapping_method: Literal["direct", "mask"]
  410. def __init__(
  411. self,
  412. alpha: float = 1,
  413. sigma: float = 50,
  414. interpolation: Literal[
  415. cv2.INTER_NEAREST,
  416. cv2.INTER_LINEAR,
  417. cv2.INTER_CUBIC,
  418. cv2.INTER_AREA,
  419. cv2.INTER_LANCZOS4,
  420. ] = cv2.INTER_LINEAR,
  421. approximate: bool = False,
  422. same_dxdy: bool = False,
  423. mask_interpolation: Literal[
  424. cv2.INTER_NEAREST,
  425. cv2.INTER_LINEAR,
  426. cv2.INTER_CUBIC,
  427. cv2.INTER_AREA,
  428. cv2.INTER_LANCZOS4,
  429. ] = cv2.INTER_NEAREST,
  430. noise_distribution: Literal["gaussian", "uniform"] = "gaussian",
  431. keypoint_remapping_method: Literal["direct", "mask"] = "mask",
  432. border_mode: Literal[
  433. cv2.BORDER_CONSTANT,
  434. cv2.BORDER_REPLICATE,
  435. cv2.BORDER_REFLECT,
  436. cv2.BORDER_WRAP,
  437. cv2.BORDER_REFLECT_101,
  438. ] = cv2.BORDER_CONSTANT,
  439. fill: tuple[float, ...] | float = 0,
  440. fill_mask: tuple[float, ...] | float = 0,
  441. p: float = 0.5,
  442. ):
  443. super().__init__(
  444. interpolation=interpolation,
  445. mask_interpolation=mask_interpolation,
  446. keypoint_remapping_method=keypoint_remapping_method,
  447. p=p,
  448. border_mode=border_mode,
  449. fill=fill,
  450. fill_mask=fill_mask,
  451. )
  452. self.alpha = alpha
  453. self.sigma = sigma
  454. self.approximate = approximate
  455. self.same_dxdy = same_dxdy
  456. self.noise_distribution = noise_distribution
  457. def get_params_dependent_on_data(
  458. self,
  459. params: dict[str, Any],
  460. data: dict[str, Any],
  461. ) -> dict[str, Any]:
  462. """Generate displacement fields for the elastic transform.
  463. Args:
  464. params (dict[str, Any]): Dictionary containing parameters for the transform.
  465. data (dict[str, Any]): Dictionary containing data for the transform.
  466. Returns:
  467. dict[str, Any]: Dictionary containing displacement fields for the elastic transform.
  468. """
  469. height, width = params["shape"][:2]
  470. kernel_size = (17, 17) if self.approximate else (0, 0)
  471. # Generate displacement fields
  472. dx, dy = fgeometric.generate_displacement_fields(
  473. (height, width),
  474. self.alpha,
  475. self.sigma,
  476. same_dxdy=self.same_dxdy,
  477. kernel_size=kernel_size,
  478. random_generator=self.random_generator,
  479. noise_distribution=self.noise_distribution,
  480. )
  481. # Vectorized map generation
  482. coords = np.stack(np.meshgrid(np.arange(width), np.arange(height)))
  483. maps = coords + np.stack([dx, dy])
  484. return {
  485. "map_x": maps[0].astype(np.float32),
  486. "map_y": maps[1].astype(np.float32),
  487. }
  488. class PiecewiseAffine(BaseDistortion):
  489. """Apply piecewise affine transformations to the input image.
  490. This augmentation places a regular grid of points on an image and randomly moves the neighborhood of these points
  491. around via affine transformations. This leads to local distortions in the image.
  492. Args:
  493. scale (tuple[float, float] | float): Standard deviation of the normal distributions. These are used to sample
  494. the random distances of the subimage's corners from the full image's corners.
  495. If scale is a single float value, the range will be (0, scale).
  496. Recommended values are in the range (0.01, 0.05) for small distortions,
  497. and (0.05, 0.1) for larger distortions. Default: (0.03, 0.05).
  498. nb_rows (tuple[int, int] | int): Number of rows of points that the regular grid should have.
  499. Must be at least 2. For large images, you might want to pick a higher value than 4.
  500. If a single int, then that value will always be used as the number of rows.
  501. If a tuple (a, b), then a value from the discrete interval [a..b] will be uniformly sampled per image.
  502. Default: 4.
  503. nb_cols (tuple[int, int] | int): Number of columns of points that the regular grid should have.
  504. Must be at least 2. For large images, you might want to pick a higher value than 4.
  505. If a single int, then that value will always be used as the number of columns.
  506. If a tuple (a, b), then a value from the discrete interval [a..b] will be uniformly sampled per image.
  507. Default: 4.
  508. interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm.
  509. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
  510. Default: cv2.INTER_LINEAR.
  511. mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
  512. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
  513. Default: cv2.INTER_NEAREST.
  514. absolute_scale (bool): If set to True, the value of the scale parameter will be treated as an absolute
  515. pixel value. If set to False, it will be treated as a fraction of the image height and width.
  516. Default: False.
  517. keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
  518. - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
  519. less accurate for large distortions. Recommended for large images or many keypoints.
  520. - "direct": Uses inverse mapping. More accurate for large distortions but slower.
  521. Default: "mask"
  522. p (float): Probability of applying the transform. Default: 0.5.
  523. Targets:
  524. image, mask, keypoints, bboxes, volume, mask3d
  525. Image types:
  526. uint8, float32
  527. Note:
  528. - This augmentation is very slow. Consider using `ElasticTransform` instead, which is at least 10x faster.
  529. - The augmentation may not always produce visible effects, especially with small scale values.
  530. - For keypoints and bounding boxes, the transformation might move them outside the image boundaries.
  531. In such cases, the keypoints will be set to (-1, -1) and the bounding boxes will be removed.
  532. Examples:
  533. >>> import numpy as np
  534. >>> import albumentations as A
  535. >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
  536. >>> transform = A.Compose([
  537. ... A.PiecewiseAffine(scale=(0.03, 0.05), nb_rows=4, nb_cols=4, p=0.5),
  538. ... ])
  539. >>> transformed = transform(image=image)
  540. >>> transformed_image = transformed["image"]
  541. """
  542. class InitSchema(BaseDistortion.InitSchema):
  543. scale: NonNegativeFloatRangeType
  544. nb_rows: tuple[int, int] | int
  545. nb_cols: tuple[int, int] | int
  546. absolute_scale: bool
  547. @field_validator("nb_rows", "nb_cols")
  548. @classmethod
  549. def _process_range(
  550. cls,
  551. value: tuple[int, int] | int,
  552. info: ValidationInfo,
  553. ) -> tuple[int, int]:
  554. bounds = 2, BIG_INTEGER
  555. result = to_tuple(value, value)
  556. check_range(result, *bounds, info.field_name)
  557. return result
  558. def __init__(
  559. self,
  560. scale: tuple[float, float] | float = (0.03, 0.05),
  561. nb_rows: tuple[int, int] | int = (4, 4),
  562. nb_cols: tuple[int, int] | int = (4, 4),
  563. interpolation: Literal[
  564. cv2.INTER_NEAREST,
  565. cv2.INTER_LINEAR,
  566. cv2.INTER_CUBIC,
  567. cv2.INTER_AREA,
  568. cv2.INTER_LANCZOS4,
  569. ] = cv2.INTER_LINEAR,
  570. mask_interpolation: Literal[
  571. cv2.INTER_NEAREST,
  572. cv2.INTER_LINEAR,
  573. cv2.INTER_CUBIC,
  574. cv2.INTER_AREA,
  575. cv2.INTER_LANCZOS4,
  576. ] = cv2.INTER_NEAREST,
  577. absolute_scale: bool = False,
  578. keypoint_remapping_method: Literal["direct", "mask"] = "mask",
  579. p: float = 0.5,
  580. border_mode: Literal[
  581. cv2.BORDER_CONSTANT,
  582. cv2.BORDER_REPLICATE,
  583. cv2.BORDER_REFLECT,
  584. cv2.BORDER_WRAP,
  585. cv2.BORDER_REFLECT_101,
  586. ] = cv2.BORDER_CONSTANT,
  587. fill: tuple[float, ...] | float = 0,
  588. fill_mask: tuple[float, ...] | float = 0,
  589. ):
  590. super().__init__(
  591. p=p,
  592. interpolation=interpolation,
  593. mask_interpolation=mask_interpolation,
  594. keypoint_remapping_method=keypoint_remapping_method,
  595. border_mode=border_mode,
  596. fill=fill,
  597. fill_mask=fill_mask,
  598. )
  599. warn(
  600. "This augmenter is very slow. Try to use ``ElasticTransform`` instead, which is at least 10x faster.",
  601. stacklevel=2,
  602. )
  603. self.scale = cast("tuple[float, float]", scale)
  604. self.nb_rows = cast("tuple[int, int]", nb_rows)
  605. self.nb_cols = cast("tuple[int, int]", nb_cols)
  606. self.absolute_scale = absolute_scale
  607. def get_params_dependent_on_data(
  608. self,
  609. params: dict[str, Any],
  610. data: dict[str, Any],
  611. ) -> dict[str, Any]:
  612. """Get the parameters dependent on the data.
  613. Args:
  614. params (dict[str, Any]): Parameters.
  615. data (dict[str, Any]): Data.
  616. Returns:
  617. dict[str, Any]: Parameters.
  618. """
  619. image_shape = params["shape"][:2]
  620. nb_rows = np.clip(self.py_random.randint(*self.nb_rows), 2, None)
  621. nb_cols = np.clip(self.py_random.randint(*self.nb_cols), 2, None)
  622. scale = self.py_random.uniform(*self.scale)
  623. map_x, map_y = fgeometric.create_piecewise_affine_maps(
  624. image_shape=image_shape,
  625. grid=(nb_rows, nb_cols),
  626. scale=scale,
  627. absolute_scale=self.absolute_scale,
  628. random_generator=self.random_generator,
  629. )
  630. return {"map_x": map_x, "map_y": map_y}
  631. class OpticalDistortion(BaseDistortion):
  632. """Apply optical distortion to images, masks, bounding boxes, and keypoints.
  633. Supports two distortion models:
  634. 1. Camera matrix model (original):
  635. Uses OpenCV's camera calibration model with k1=k2=k distortion coefficients
  636. 2. Fisheye model:
  637. Direct radial distortion: r_dist = r * (1 + gamma * r²)
  638. Args:
  639. distort_limit (float | tuple[float, float]): Range of distortion coefficient.
  640. For camera model: recommended range (-0.05, 0.05)
  641. For fisheye model: recommended range (-0.3, 0.3)
  642. Default: (-0.05, 0.05)
  643. mode (Literal['camera', 'fisheye']): Distortion model to use:
  644. - 'camera': Original camera matrix model
  645. - 'fisheye': Fisheye lens model
  646. Default: 'camera'
  647. interpolation (OpenCV flag): Interpolation method used for image transformation.
  648. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC,
  649. cv2.INTER_AREA, cv2.INTER_LANCZOS4. Default: cv2.INTER_LINEAR.
  650. mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
  651. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
  652. Default: cv2.INTER_NEAREST.
  653. keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
  654. - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
  655. less accurate for large distortions. Recommended for large images or many keypoints.
  656. - "direct": Uses inverse mapping. More accurate for large distortions but slower.
  657. Default: "mask"
  658. p (float): Probability of applying the transform. Default: 0.5.
  659. Targets:
  660. image, mask, bboxes, keypoints, volume, mask3d
  661. Image types:
  662. uint8, float32
  663. Note:
  664. - The distortion is applied using OpenCV's initUndistortRectifyMap and remap functions.
  665. - The distortion coefficient (k) is randomly sampled from the distort_limit range.
  666. - Bounding boxes and keypoints are transformed along with the image to maintain consistency.
  667. - Fisheye model directly applies radial distortion
  668. Examples:
  669. >>> import albumentations as A
  670. >>> transform = A.Compose([
  671. ... A.OpticalDistortion(distort_limit=0.1, p=1.0),
  672. ... ])
  673. >>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
  674. >>> transformed_image = transformed['image']
  675. >>> transformed_mask = transformed['mask']
  676. >>> transformed_bboxes = transformed['bboxes']
  677. >>> transformed_keypoints = transformed['keypoints']
  678. """
  679. class InitSchema(BaseDistortion.InitSchema):
  680. distort_limit: SymmetricRangeType
  681. mode: Literal["camera", "fisheye"]
  682. keypoint_remapping_method: Literal["direct", "mask"]
  683. def __init__(
  684. self,
  685. distort_limit: tuple[float, float] | float = (-0.05, 0.05),
  686. interpolation: Literal[
  687. cv2.INTER_NEAREST,
  688. cv2.INTER_LINEAR,
  689. cv2.INTER_CUBIC,
  690. cv2.INTER_AREA,
  691. cv2.INTER_LANCZOS4,
  692. ] = cv2.INTER_LINEAR,
  693. mask_interpolation: Literal[
  694. cv2.INTER_NEAREST,
  695. cv2.INTER_LINEAR,
  696. cv2.INTER_CUBIC,
  697. cv2.INTER_AREA,
  698. cv2.INTER_LANCZOS4,
  699. ] = cv2.INTER_NEAREST,
  700. mode: Literal["camera", "fisheye"] = "camera",
  701. keypoint_remapping_method: Literal["direct", "mask"] = "mask",
  702. p: float = 0.5,
  703. border_mode: Literal[
  704. cv2.BORDER_CONSTANT,
  705. cv2.BORDER_REPLICATE,
  706. cv2.BORDER_REFLECT,
  707. cv2.BORDER_WRAP,
  708. cv2.BORDER_REFLECT_101,
  709. ] = cv2.BORDER_CONSTANT,
  710. fill: tuple[float, ...] | float = 0,
  711. fill_mask: tuple[float, ...] | float = 0,
  712. ):
  713. super().__init__(
  714. interpolation=interpolation,
  715. mask_interpolation=mask_interpolation,
  716. keypoint_remapping_method=keypoint_remapping_method,
  717. p=p,
  718. border_mode=border_mode,
  719. fill=fill,
  720. fill_mask=fill_mask,
  721. )
  722. self.distort_limit = cast("tuple[float, float]", distort_limit)
  723. self.mode = mode
  724. def get_params_dependent_on_data(
  725. self,
  726. params: dict[str, Any],
  727. data: dict[str, Any],
  728. ) -> dict[str, Any]:
  729. """Get the parameters dependent on the data.
  730. Args:
  731. params (dict[str, Any]): Parameters.
  732. data (dict[str, Any]): Data.
  733. Returns:
  734. dict[str, Any]: Parameters.
  735. """
  736. image_shape = params["shape"][:2]
  737. # Get distortion coefficient
  738. k = self.py_random.uniform(*self.distort_limit)
  739. # Get distortion maps based on mode
  740. if self.mode == "camera":
  741. map_x, map_y = fgeometric.get_camera_matrix_distortion_maps(
  742. image_shape,
  743. k,
  744. )
  745. else: # fisheye
  746. map_x, map_y = fgeometric.get_fisheye_distortion_maps(
  747. image_shape,
  748. k,
  749. )
  750. return {"map_x": map_x, "map_y": map_y}
  751. class GridDistortion(BaseDistortion):
  752. """Apply grid distortion to images, masks, bounding boxes, and keypoints.
  753. This transformation divides the image into a grid and randomly distorts each cell,
  754. creating localized warping effects. It's particularly useful for data augmentation
  755. in tasks like medical image analysis, OCR, and other domains where local geometric
  756. variations are meaningful.
  757. Args:
  758. num_steps (int): Number of grid cells on each side of the image. Higher values
  759. create more granular distortions. Must be at least 1. Default: 5.
  760. distort_limit (float or tuple[float, float]): Range of distortion. If a single float
  761. is provided, the range will be (-distort_limit, distort_limit). Higher values
  762. create stronger distortions. Should be in the range of -1 to 1.
  763. Default: (-0.3, 0.3).
  764. interpolation (int): OpenCV interpolation method used for image transformation.
  765. Options include cv2.INTER_LINEAR, cv2.INTER_CUBIC, etc. Default: cv2.INTER_LINEAR.
  766. normalized (bool): If True, ensures that the distortion does not move pixels
  767. outside the image boundaries. This can result in less extreme distortions
  768. but guarantees that no information is lost. Default: True.
  769. mask_interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm for mask.
  770. Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
  771. Default: cv2.INTER_NEAREST.
  772. keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
  773. - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
  774. less accurate for large distortions. Recommended for large images or many keypoints.
  775. - "direct": Uses inverse mapping. More accurate for large distortions but slower.
  776. Default: "mask"
  777. p (float): Probability of applying the transform. Default: 0.5.
  778. Targets:
  779. image, mask, bboxes, keypoints, volume, mask3d
  780. Image types:
  781. uint8, float32
  782. Note:
  783. - The same distortion is applied to all targets (image, mask, bboxes, keypoints)
  784. to maintain consistency.
  785. - When normalized=True, the distortion is adjusted to ensure all pixels remain
  786. within the image boundaries.
  787. Examples:
  788. >>> import albumentations as A
  789. >>> transform = A.Compose([
  790. ... A.GridDistortion(num_steps=5, distort_limit=0.3, p=1.0),
  791. ... ])
  792. >>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
  793. >>> transformed_image = transformed['image']
  794. >>> transformed_mask = transformed['mask']
  795. >>> transformed_bboxes = transformed['bboxes']
  796. >>> transformed_keypoints = transformed['keypoints']
  797. """
  798. class InitSchema(BaseDistortion.InitSchema):
  799. num_steps: Annotated[int, Field(ge=1)]
  800. distort_limit: SymmetricRangeType
  801. normalized: bool
  802. keypoint_remapping_method: Literal["direct", "mask"]
  803. @field_validator("distort_limit")
  804. @classmethod
  805. def _check_limits(
  806. cls,
  807. v: tuple[float, float],
  808. info: ValidationInfo,
  809. ) -> tuple[float, float]:
  810. bounds = -1, 1
  811. result = to_tuple(v)
  812. check_range(result, *bounds, info.field_name)
  813. return result
  814. def __init__(
  815. self,
  816. num_steps: int = 5,
  817. distort_limit: tuple[float, float] | float = (-0.3, 0.3),
  818. interpolation: Literal[
  819. cv2.INTER_NEAREST,
  820. cv2.INTER_LINEAR,
  821. cv2.INTER_CUBIC,
  822. cv2.INTER_AREA,
  823. cv2.INTER_LANCZOS4,
  824. ] = cv2.INTER_LINEAR,
  825. normalized: bool = True,
  826. mask_interpolation: Literal[
  827. cv2.INTER_NEAREST,
  828. cv2.INTER_LINEAR,
  829. cv2.INTER_CUBIC,
  830. cv2.INTER_AREA,
  831. cv2.INTER_LANCZOS4,
  832. ] = cv2.INTER_NEAREST,
  833. keypoint_remapping_method: Literal["direct", "mask"] = "mask",
  834. p: float = 0.5,
  835. border_mode: Literal[
  836. cv2.BORDER_CONSTANT,
  837. cv2.BORDER_REPLICATE,
  838. cv2.BORDER_REFLECT,
  839. cv2.BORDER_WRAP,
  840. cv2.BORDER_REFLECT_101,
  841. ] = cv2.BORDER_CONSTANT,
  842. fill: tuple[float, ...] | float = 0,
  843. fill_mask: tuple[float, ...] | float = 0,
  844. ):
  845. super().__init__(
  846. interpolation=interpolation,
  847. mask_interpolation=mask_interpolation,
  848. keypoint_remapping_method=keypoint_remapping_method,
  849. p=p,
  850. border_mode=border_mode,
  851. fill=fill,
  852. fill_mask=fill_mask,
  853. )
  854. self.num_steps = num_steps
  855. self.distort_limit = cast("tuple[float, float]", distort_limit)
  856. self.normalized = normalized
  857. def get_params_dependent_on_data(
  858. self,
  859. params: dict[str, Any],
  860. data: dict[str, Any],
  861. ) -> dict[str, Any]:
  862. """Get the parameters dependent on the data.
  863. Args:
  864. params (dict[str, Any]): Parameters.
  865. data (dict[str, Any]): Data.
  866. Returns:
  867. dict[str, Any]: Parameters.
  868. """
  869. image_shape = params["shape"][:2]
  870. steps_x = [1 + self.py_random.uniform(*self.distort_limit) for _ in range(self.num_steps + 1)]
  871. steps_y = [1 + self.py_random.uniform(*self.distort_limit) for _ in range(self.num_steps + 1)]
  872. if self.normalized:
  873. normalized_params = fgeometric.normalize_grid_distortion_steps(
  874. image_shape,
  875. self.num_steps,
  876. steps_x,
  877. steps_y,
  878. )
  879. steps_x, steps_y = (
  880. normalized_params["steps_x"],
  881. normalized_params["steps_y"],
  882. )
  883. map_x, map_y = fgeometric.generate_grid(
  884. image_shape,
  885. steps_x,
  886. steps_y,
  887. self.num_steps,
  888. )
  889. return {"map_x": map_x, "map_y": map_y}
  890. class ThinPlateSpline(BaseDistortion):
  891. r"""Apply Thin Plate Spline (TPS) transformation to create smooth, non-rigid deformations.
  892. Imagine the image printed on a thin metal plate that can be bent and warped smoothly:
  893. - Control points act like pins pushing or pulling the plate
  894. - The plate resists sharp bending, creating smooth deformations
  895. - The transformation maintains continuity (no tears or folds)
  896. - Areas between control points are interpolated naturally
  897. The transform works by:
  898. 1. Creating a regular grid of control points (like pins in the plate)
  899. 2. Randomly displacing these points (like pushing/pulling the pins)
  900. 3. Computing a smooth interpolation (like the plate bending)
  901. 4. Applying the resulting deformation to the image
  902. Args:
  903. scale_range (tuple[float, float]): Range for random displacement of control points.
  904. Values should be in [0.0, 1.0]:
  905. - 0.0: No displacement (identity transform)
  906. - 0.1: Subtle warping
  907. - 0.2-0.4: Moderate deformation (recommended range)
  908. - 0.5+: Strong warping
  909. Default: (0.2, 0.4)
  910. num_control_points (int): Number of control points per side.
  911. Creates a grid of num_control_points x num_control_points points.
  912. - 2: Minimal deformation (affine-like)
  913. - 3-4: Moderate flexibility (recommended)
  914. - 5+: More local deformation control
  915. Must be >= 2. Default: 4
  916. interpolation (int): OpenCV interpolation flag. Used for image sampling.
  917. See also: cv2.INTER_*
  918. Default: cv2.INTER_LINEAR
  919. mask_interpolation (int): OpenCV interpolation flag. Used for mask sampling.
  920. See also: cv2.INTER_*
  921. Default: cv2.INTER_NEAREST
  922. keypoint_remapping_method (Literal["direct", "mask"]): Method to use for keypoint remapping.
  923. - "mask": Uses mask-based remapping. Faster, especially for many keypoints, but may be
  924. less accurate for large distortions. Recommended for large images or many keypoints.
  925. - "direct": Uses inverse mapping. More accurate for large distortions but slower.
  926. Default: "mask"
  927. p (float): Probability of applying the transform. Default: 0.5
  928. Targets:
  929. image, mask, keypoints, bboxes, volume, mask3d
  930. Image types:
  931. uint8, float32
  932. Note:
  933. - The transformation preserves smoothness and continuity
  934. - Stronger scale values may create more extreme deformations
  935. - Higher number of control points allows more local deformations
  936. - The same deformation is applied consistently to all targets
  937. Examples:
  938. >>> import numpy as np
  939. >>> import albumentations as A
  940. >>> import cv2
  941. >>>
  942. >>> # Create sample data
  943. >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
  944. >>> mask = np.zeros((100, 100), dtype=np.uint8)
  945. >>> mask[25:75, 25:75] = 1 # Square mask
  946. >>> bboxes = np.array([[10, 10, 40, 40]]) # Single box
  947. >>> bbox_labels = [1]
  948. >>> keypoints = np.array([[50, 50]]) # Single keypoint at center
  949. >>> keypoint_labels = [0]
  950. >>>
  951. >>> # Set up transform with Compose to handle all targets
  952. >>> transform = A.Compose([
  953. ... A.ThinPlateSpline(scale_range=(0.2, 0.4), p=1.0)
  954. ... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
  955. ... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
  956. >>>
  957. >>> # Apply to all targets
  958. >>> result = transform(
  959. ... image=image,
  960. ... mask=mask,
  961. ... bboxes=bboxes,
  962. ... bbox_labels=bbox_labels,
  963. ... keypoints=keypoints,
  964. ... keypoint_labels=keypoint_labels
  965. ... )
  966. >>>
  967. >>> # Access transformed results
  968. >>> transformed_image = result['image']
  969. >>> transformed_mask = result['mask']
  970. >>> transformed_bboxes = result['bboxes']
  971. >>> transformed_bbox_labels = result['bbox_labels']
  972. >>> transformed_keypoints = result['keypoints']
  973. >>> transformed_keypoint_labels = result['keypoint_labels']
  974. References:
  975. - "Principal Warps: Thin-Plate Splines and the Decomposition of Deformations"
  976. by F.L. Bookstein
  977. https://doi.org/10.1109/34.24792
  978. - Thin Plate Splines in Computer Vision:
  979. https://en.wikipedia.org/wiki/Thin_plate_spline
  980. - Similar implementation in Kornia:
  981. https://kornia.readthedocs.io/en/latest/augmentation.html#kornia.augmentation.RandomThinPlateSpline
  982. See Also:
  983. - ElasticTransform: For different type of non-rigid deformation
  984. - GridDistortion: For grid-based warping
  985. - OpticalDistortion: For lens-like distortions
  986. """
  987. class InitSchema(BaseDistortion.InitSchema):
  988. scale_range: Annotated[tuple[float, float], AfterValidator(check_range_bounds(0, 1))]
  989. num_control_points: int = Field(ge=2)
  990. keypoint_remapping_method: Literal["direct", "mask"]
  991. def __init__(
  992. self,
  993. scale_range: tuple[float, float] = (0.2, 0.4),
  994. num_control_points: int = 4,
  995. interpolation: Literal[
  996. cv2.INTER_NEAREST,
  997. cv2.INTER_LINEAR,
  998. cv2.INTER_CUBIC,
  999. cv2.INTER_AREA,
  1000. cv2.INTER_LANCZOS4,
  1001. ] = cv2.INTER_LINEAR,
  1002. mask_interpolation: Literal[
  1003. cv2.INTER_NEAREST,
  1004. cv2.INTER_LINEAR,
  1005. cv2.INTER_CUBIC,
  1006. cv2.INTER_AREA,
  1007. cv2.INTER_LANCZOS4,
  1008. ] = cv2.INTER_NEAREST,
  1009. keypoint_remapping_method: Literal["direct", "mask"] = "mask",
  1010. p: float = 0.5,
  1011. border_mode: Literal[
  1012. cv2.BORDER_CONSTANT,
  1013. cv2.BORDER_REPLICATE,
  1014. cv2.BORDER_REFLECT,
  1015. cv2.BORDER_WRAP,
  1016. cv2.BORDER_REFLECT_101,
  1017. ] = cv2.BORDER_CONSTANT,
  1018. fill: tuple[float, ...] | float = 0,
  1019. fill_mask: tuple[float, ...] | float = 0,
  1020. ):
  1021. super().__init__(
  1022. interpolation=interpolation,
  1023. mask_interpolation=mask_interpolation,
  1024. keypoint_remapping_method=keypoint_remapping_method,
  1025. p=p,
  1026. border_mode=border_mode,
  1027. fill=fill,
  1028. fill_mask=fill_mask,
  1029. )
  1030. self.scale_range = scale_range
  1031. self.num_control_points = num_control_points
  1032. def get_params_dependent_on_data(
  1033. self,
  1034. params: dict[str, Any],
  1035. data: dict[str, Any],
  1036. ) -> dict[str, Any]:
  1037. """Get the parameters dependent on the data.
  1038. Args:
  1039. params (dict[str, Any]): Parameters.
  1040. data (dict[str, Any]): Data.
  1041. Returns:
  1042. dict[str, Any]: Parameters.
  1043. """
  1044. height, width = params["shape"][:2]
  1045. src_points = fgeometric.generate_control_points(self.num_control_points)
  1046. # Add random displacement to destination points
  1047. scale = self.py_random.uniform(*self.scale_range) / 10
  1048. dst_points = src_points + self.random_generator.normal(
  1049. 0,
  1050. scale,
  1051. src_points.shape,
  1052. )
  1053. # Compute TPS weights
  1054. weights, affine = fgeometric.compute_tps_weights(src_points, dst_points)
  1055. # Create grid of points
  1056. x, y = np.meshgrid(np.arange(width), np.arange(height))
  1057. points = np.stack([x.flatten(), y.flatten()], axis=1).astype(np.float32)
  1058. # Transform points
  1059. transformed = fgeometric.tps_transform(
  1060. points / [width, height],
  1061. src_points,
  1062. weights,
  1063. affine,
  1064. )
  1065. transformed *= [width, height]
  1066. return {
  1067. "map_x": transformed[:, 0].reshape(height, width).astype(np.float32),
  1068. "map_y": transformed[:, 1].reshape(height, width).astype(np.float32),
  1069. }