coarse_dropout.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. """Implementation of coarse dropout and random erasing augmentations.
  2. This module provides several variations of coarse dropout augmentations, which drop out
  3. rectangular regions from images. It includes CoarseDropout for randomly placed dropouts,
  4. ConstrainedCoarseDropout for dropping out regions based on masks or bounding boxes,
  5. and Erasing for random erasing augmentation. These techniques help models become more
  6. robust to occlusions and varying object completeness.
  7. """
  8. from __future__ import annotations
  9. from typing import Annotated, Any, Literal
  10. from warnings import warn
  11. import numpy as np
  12. from pydantic import AfterValidator
  13. import albumentations.augmentations.dropout.functional as fdropout
  14. from albumentations.augmentations.dropout.transforms import BaseDropout
  15. from albumentations.core.bbox_utils import denormalize_bboxes
  16. from albumentations.core.pydantic import check_range_bounds, nondecreasing
  17. __all__ = ["CoarseDropout", "ConstrainedCoarseDropout", "Erasing"]
  18. class CoarseDropout(BaseDropout):
  19. """CoarseDropout randomly drops out rectangular regions from the image and optionally,
  20. the corresponding regions in an associated mask, to simulate occlusion and
  21. varied object sizes found in real-world settings.
  22. This transformation is an evolution of CutOut and RandomErasing, offering more
  23. flexibility in the size, number of dropout regions, and fill values.
  24. Args:
  25. num_holes_range (tuple[int, int]): Range (min, max) for the number of rectangular
  26. regions to drop out. Default: (1, 1)
  27. hole_height_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the height
  28. of dropout regions. If int, specifies absolute pixel values. If float,
  29. interpreted as a fraction of the image height. Default: (0.1, 0.2)
  30. hole_width_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the width
  31. of dropout regions. If int, specifies absolute pixel values. If float,
  32. interpreted as a fraction of the image width. Default: (0.1, 0.2)
  33. fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
  34. Value for the dropped pixels. Can be:
  35. - int or float: all channels are filled with this value
  36. - tuple: tuple of values for each channel
  37. - 'random': each pixel is filled with random values
  38. - 'random_uniform': each hole is filled with a single random color
  39. - 'inpaint_telea': uses OpenCV Telea inpainting method
  40. - 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
  41. Default: 0
  42. fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the mask.
  43. If None, mask regions corresponding to image dropouts are unchanged. Default: None
  44. p (float): Probability of applying the transform. Default: 0.5
  45. Targets:
  46. image, mask, bboxes, keypoints, volume, mask3d
  47. Image types:
  48. uint8, float32
  49. Note:
  50. - The actual number and size of dropout regions are randomly chosen within the specified ranges for each
  51. application.
  52. - When using float values for hole_height_range and hole_width_range, ensure they are between 0 and 1.
  53. - This implementation includes deprecation warnings for older parameter names (min_holes, max_holes, etc.).
  54. - Inpainting methods ('inpaint_telea', 'inpaint_ns') work only with grayscale or RGB images.
  55. - For 'random_uniform' fill, each hole gets a single random color, unlike 'random' where each pixel
  56. gets its own random value.
  57. Example:
  58. >>> import numpy as np
  59. >>> import albumentations as A
  60. >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
  61. >>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
  62. >>> # Example with random uniform fill
  63. >>> aug_random = A.CoarseDropout(
  64. ... num_holes_range=(3, 6),
  65. ... hole_height_range=(10, 20),
  66. ... hole_width_range=(10, 20),
  67. ... fill="random_uniform",
  68. ... p=1.0
  69. ... )
  70. >>> # Example with inpainting
  71. >>> aug_inpaint = A.CoarseDropout(
  72. ... num_holes_range=(3, 6),
  73. ... hole_height_range=(10, 20),
  74. ... hole_width_range=(10, 20),
  75. ... fill="inpaint_ns",
  76. ... p=1.0
  77. ... )
  78. >>> transformed = aug_random(image=image, mask=mask)
  79. >>> transformed_image, transformed_mask = transformed["image"], transformed["mask"]
  80. References:
  81. - CutOut: https://arxiv.org/abs/1708.04552
  82. - Random Erasing: https://arxiv.org/abs/1708.04896
  83. - OpenCV Inpainting methods: https://docs.opencv.org/master/df/d3d/tutorial_py_inpainting.html
  84. """
  85. class InitSchema(BaseDropout.InitSchema):
  86. num_holes_range: Annotated[
  87. tuple[int, int],
  88. AfterValidator(check_range_bounds(1, None)),
  89. AfterValidator(nondecreasing),
  90. ]
  91. hole_height_range: Annotated[
  92. tuple[float, float] | tuple[int, int],
  93. AfterValidator(nondecreasing),
  94. AfterValidator(check_range_bounds(0, None)),
  95. ]
  96. hole_width_range: Annotated[
  97. tuple[float, float] | tuple[int, int],
  98. AfterValidator(nondecreasing),
  99. AfterValidator(check_range_bounds(0, None)),
  100. ]
  101. def __init__(
  102. self,
  103. num_holes_range: tuple[int, int] = (1, 2),
  104. hole_height_range: tuple[float, float] | tuple[int, int] = (0.1, 0.2),
  105. hole_width_range: tuple[float, float] | tuple[int, int] = (0.1, 0.2),
  106. fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
  107. fill_mask: tuple[float, ...] | float | None = None,
  108. p: float = 0.5,
  109. ):
  110. super().__init__(fill=fill, fill_mask=fill_mask, p=p)
  111. self.num_holes_range = num_holes_range
  112. self.hole_height_range = hole_height_range
  113. self.hole_width_range = hole_width_range
  114. def calculate_hole_dimensions(
  115. self,
  116. image_shape: tuple[int, int],
  117. height_range: tuple[float, float] | tuple[int, int],
  118. width_range: tuple[float, float] | tuple[int, int],
  119. size: int,
  120. ) -> tuple[np.ndarray, np.ndarray]:
  121. """Calculate random hole dimensions based on the provided ranges."""
  122. height, width = image_shape[:2]
  123. if height_range[1] >= 1:
  124. min_height = height_range[0]
  125. max_height = min(height_range[1], height)
  126. min_width = width_range[0]
  127. max_width = min(width_range[1], width)
  128. hole_heights = self.random_generator.integers(int(min_height), int(max_height + 1), size=size)
  129. hole_widths = self.random_generator.integers(int(min_width), int(max_width + 1), size=size)
  130. else: # Assume float
  131. hole_heights = (height * self.random_generator.uniform(*height_range, size=size)).astype(int)
  132. hole_widths = (width * self.random_generator.uniform(*width_range, size=size)).astype(int)
  133. return hole_heights, hole_widths
  134. def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
  135. """Get parameters dependent on the data.
  136. Args:
  137. params (dict[str, Any]): Dictionary containing parameters.
  138. data (dict[str, Any]): Dictionary containing data.
  139. Returns:
  140. dict[str, Any]: Dictionary with parameters for transformation.
  141. """
  142. image_shape = params["shape"][:2]
  143. num_holes = self.py_random.randint(*self.num_holes_range)
  144. hole_heights, hole_widths = self.calculate_hole_dimensions(
  145. image_shape,
  146. self.hole_height_range,
  147. self.hole_width_range,
  148. size=num_holes,
  149. )
  150. height, width = image_shape[:2]
  151. y_min = self.random_generator.integers(0, height - hole_heights + 1, size=num_holes)
  152. x_min = self.random_generator.integers(0, width - hole_widths + 1, size=num_holes)
  153. y_max = y_min + hole_heights
  154. x_max = x_min + hole_widths
  155. holes = np.stack([x_min, y_min, x_max, y_max], axis=-1)
  156. return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
  157. class Erasing(BaseDropout):
  158. """Randomly erases rectangular regions in an image, following the Random Erasing Data Augmentation technique.
  159. This augmentation helps improve model robustness by randomly masking out rectangular regions in the image,
  160. simulating occlusions and encouraging the model to learn from partial information. It's particularly
  161. effective for image classification and person re-identification tasks.
  162. Args:
  163. scale (tuple[float, float]): Range for the proportion of image area to erase.
  164. The actual area will be randomly sampled from (scale[0] * image_area, scale[1] * image_area).
  165. Default: (0.02, 0.33)
  166. ratio (tuple[float, float]): Range for the aspect ratio (width/height) of the erased region.
  167. The actual ratio will be randomly sampled from (ratio[0], ratio[1]).
  168. Default: (0.3, 3.3)
  169. fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
  170. Value used to fill the erased regions. Can be:
  171. - int or float: fills all channels with this value
  172. - tuple: fills each channel with corresponding value
  173. - "random": fills each pixel with random values
  174. - "random_uniform": fills entire erased region with a single random color
  175. - "inpaint_telea": uses OpenCV Telea inpainting method
  176. - "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
  177. Default: 0
  178. fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
  179. If None, mask regions are not modified. Default: None
  180. p (float): Probability of applying the transform. Default: 0.5
  181. Targets:
  182. image, mask, bboxes, keypoints, volume, mask3d
  183. Image types:
  184. uint8, float32
  185. Note:
  186. - The transform attempts to find valid erasing parameters up to 10 times.
  187. If unsuccessful, no erasing is performed.
  188. - The actual erased area and aspect ratio are randomly sampled within
  189. the specified ranges for each application.
  190. - When using inpainting methods, only grayscale or RGB images are supported.
  191. Example:
  192. >>> import numpy as np
  193. >>> import albumentations as A
  194. >>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
  195. >>> # Basic usage with default parameters
  196. >>> transform = A.Erasing()
  197. >>> transformed = transform(image=image)
  198. >>> # Custom configuration
  199. >>> transform = A.Erasing(
  200. ... scale=(0.1, 0.4),
  201. ... ratio=(0.5, 2.0),
  202. ... fill_value="random_uniform",
  203. ... p=1.0
  204. ... )
  205. >>> transformed = transform(image=image)
  206. References:
  207. - Paper: https://arxiv.org/abs/1708.04896
  208. - Implementation inspired by torchvision:
  209. https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.RandomErasing
  210. """
  211. class InitSchema(BaseDropout.InitSchema):
  212. scale: Annotated[
  213. tuple[float, float],
  214. AfterValidator(nondecreasing),
  215. AfterValidator(check_range_bounds(0, None)),
  216. ]
  217. ratio: Annotated[
  218. tuple[float, float],
  219. AfterValidator(nondecreasing),
  220. AfterValidator(check_range_bounds(0, None)),
  221. ]
  222. def __init__(
  223. self,
  224. scale: tuple[float, float] = (0.02, 0.33),
  225. ratio: tuple[float, float] = (0.3, 3.3),
  226. fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
  227. fill_mask: tuple[float, ...] | float | None = None,
  228. p: float = 0.5,
  229. ):
  230. super().__init__(fill=fill, fill_mask=fill_mask, p=p)
  231. self.scale = scale
  232. self.ratio = ratio
  233. def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
  234. """Calculate erasing parameters using direct mathematical derivation.
  235. Given:
  236. - Image dimensions (H, W)
  237. - Target area (A)
  238. - Aspect ratio (r = w/h)
  239. We know:
  240. - h * w = A (area equation)
  241. - w = r * h (aspect ratio equation)
  242. Therefore:
  243. - h * (r * h) = A
  244. - h² = A/r
  245. - h = sqrt(A/r)
  246. - w = r * sqrt(A/r) = sqrt(A*r)
  247. """
  248. height, width = params["shape"][:2]
  249. total_area = height * width
  250. # Calculate maximum valid area based on dimensions and aspect ratio
  251. max_area = total_area * self.scale[1]
  252. min_area = total_area * self.scale[0]
  253. # For each aspect ratio r, the maximum area is constrained by:
  254. # h = sqrt(A/r) ≤ H and w = sqrt(A*r) ≤ W
  255. # Therefore: A ≤ min(r*H², W²/r)
  256. r_min, r_max = self.ratio
  257. def area_constraint_h(r: float) -> float:
  258. return r * height * height
  259. def area_constraint_w(r: float) -> float:
  260. return width * width / r
  261. # Find maximum valid area considering aspect ratio constraints
  262. max_area_h = min(area_constraint_h(r_min), area_constraint_h(r_max))
  263. max_area_w = min(area_constraint_w(r_min), area_constraint_w(r_max))
  264. max_valid_area = min(max_area, max_area_h, max_area_w)
  265. if max_valid_area < min_area:
  266. return {"holes": np.array([], dtype=np.int32).reshape((0, 4))}
  267. # Sample valid area and aspect ratio
  268. erase_area = self.py_random.uniform(min_area, max_valid_area)
  269. # Calculate valid aspect ratio range for this area
  270. max_r = min(r_max, width * width / erase_area)
  271. min_r = max(r_min, erase_area / (height * height))
  272. if min_r > max_r:
  273. return {"holes": np.array([], dtype=np.int32).reshape((0, 4))}
  274. aspect_ratio = self.py_random.uniform(min_r, max_r)
  275. # Calculate dimensions
  276. h = round(np.sqrt(erase_area / aspect_ratio))
  277. w = round(np.sqrt(erase_area * aspect_ratio))
  278. # Sample position
  279. top = self.py_random.randint(0, height - h)
  280. left = self.py_random.randint(0, width - w)
  281. holes = np.array([[left, top, left + w, top + h]], dtype=np.int32)
  282. return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
  283. class ConstrainedCoarseDropout(BaseDropout):
  284. """Applies coarse dropout to regions containing specific objects in the image.
  285. This augmentation creates holes (dropout regions) for each target object in the image.
  286. Objects can be specified either by their class indices in a segmentation mask or
  287. by their labels in bounding box annotations.
  288. The hole generation differs between mask and box modes:
  289. Mask mode:
  290. 1. For each connected component in the mask matching target indices:
  291. - Samples N points randomly from within the object region (with replacement)
  292. - Creates holes centered at these points
  293. - Hole sizes are proportional to sqrt(component area), not total object area
  294. - Each component's holes are sized based on its own area
  295. Box mode:
  296. 1. For each bounding box matching target labels:
  297. - Creates N holes with random positions inside the box
  298. - Hole sizes are proportional to the box dimensions
  299. In both modes:
  300. - N is sampled once from num_holes_range and used for all objects
  301. - For example, if num_holes_range=(2,4) and 3 is sampled:
  302. * With 3 target objects, you'll get exactly 3 holes per object (9 total)
  303. * Holes may overlap within or between objects
  304. * All holes are clipped to image boundaries
  305. Args:
  306. num_holes_range (tuple[int, int]): Range for number of holes per object (min, max)
  307. hole_height_range (tuple[float, float]): Range for hole height as proportion
  308. of object height/size (min, max). E.g., (0.2, 0.4) means:
  309. - For boxes: 20-40% of box height
  310. - For masks: 20-40% of sqrt(component area)
  311. hole_width_range (tuple[float, float]): Range for hole width, similar to height
  312. fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
  313. Value used to fill the erased regions. Can be:
  314. - int or float: fills all channels with this value
  315. - tuple: fills each channel with corresponding value
  316. - "random": fills each pixel with random values
  317. - "random_uniform": fills entire erased region with a single random color
  318. - "inpaint_telea": uses OpenCV Telea inpainting method
  319. - "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
  320. Default: 0
  321. fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
  322. If None, mask regions are not modified. Default: None
  323. p (float): Probability of applying the transform
  324. mask_indices (List[int], optional): List of class indices in segmentation mask to target.
  325. Only objects of these classes will be considered for hole placement.
  326. bbox_labels (List[str | int | float], optional): List of object labels in bbox
  327. annotations to target. String labels will be automatically encoded.
  328. When multiple label fields are specified in BboxParams, only the first
  329. label field is used for filtering.
  330. Targets:
  331. image, mask, bboxes, keypoints, volume, mask3d
  332. Image types:
  333. uint8, float32
  334. Requires one of:
  335. - 'mask' key with segmentation mask where:
  336. * 0 represents background
  337. * Non-zero values represent different object instances/classes
  338. * Values must correspond to mask_indices
  339. - 'bboxes' key with bounding boxes in format [x_min, y_min, x_max, y_max, label, ...]
  340. Note:
  341. At least one of mask_indices or bbox_labels must be provided.
  342. If both are provided, mask_indices takes precedence.
  343. Examples:
  344. >>> # Using segmentation mask
  345. >>> transform = ConstrainedCoarseDropout(
  346. ... num_holes_range=(2, 4), # 2-4 holes per object
  347. ... hole_height_range=(0.2, 0.4), # 20-40% of sqrt(object area)
  348. ... hole_width_range=(0.2, 0.4), # 20-40% of sqrt(object area)
  349. ... mask_indices=[1, 2], # Target objects of class 1 and 2
  350. ... fill=0, # Fill holes with black
  351. ... )
  352. >>> # Apply to image and its segmentation mask
  353. >>> transformed = transform(image=image, mask=mask)
  354. >>> # Using bounding boxes with Compose
  355. >>> transform = A.Compose([
  356. ... ConstrainedCoarseDropout(
  357. ... num_holes_range=(1, 3),
  358. ... hole_height_range=(0.3, 0.5), # 30-50% of box height
  359. ... hole_width_range=(0.3, 0.5), # 30-50% of box width
  360. ... bbox_labels=['person'], # Target people
  361. ... fill=127, # Fill holes with gray
  362. ... )
  363. ... ], bbox_params=A.BboxParams(
  364. ... format='pascal_voc', # [x_min, y_min, x_max, y_max]
  365. ... label_fields=['labels'] # Specify field containing labels
  366. ... ))
  367. >>> # Apply to image and its bounding boxes
  368. >>> transformed = transform(
  369. ... image=image,
  370. ... bboxes=[[0, 0, 100, 100, 'car'], [150, 150, 300, 300, 'person']],
  371. ... labels=['car', 'person']
  372. ... )
  373. """
  374. class InitSchema(BaseDropout.InitSchema):
  375. num_holes_range: Annotated[
  376. tuple[int, int],
  377. AfterValidator(check_range_bounds(1, None)),
  378. AfterValidator(nondecreasing),
  379. ]
  380. hole_height_range: Annotated[
  381. tuple[float, float],
  382. AfterValidator(nondecreasing),
  383. AfterValidator(check_range_bounds(0.0, 1.0)),
  384. ]
  385. hole_width_range: Annotated[
  386. tuple[float, float],
  387. AfterValidator(nondecreasing),
  388. AfterValidator(check_range_bounds(0.0, 1.0)),
  389. ]
  390. mask_indices: Annotated[
  391. list[int] | None,
  392. AfterValidator(check_range_bounds(1, None)),
  393. ]
  394. bbox_labels: list[str | int | float] | None = None
  395. def __init__(
  396. self,
  397. num_holes_range: tuple[int, int] = (1, 1),
  398. hole_height_range: tuple[float, float] = (0.1, 0.1),
  399. hole_width_range: tuple[float, float] = (0.1, 0.1),
  400. fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
  401. fill_mask: tuple[float, ...] | float | None = None,
  402. p: float = 0.5,
  403. mask_indices: list[int] | None = None,
  404. bbox_labels: list[str | int | float] | None = None,
  405. ):
  406. super().__init__(fill=fill, fill_mask=fill_mask, p=p)
  407. self.num_holes_range = num_holes_range
  408. self.hole_height_range = hole_height_range
  409. self.hole_width_range = hole_width_range
  410. self.mask_indices = mask_indices
  411. self.bbox_labels = bbox_labels
  412. def get_boxes_from_bboxes(self, bboxes: np.ndarray) -> np.ndarray | None:
  413. """Get bounding boxes that match specified labels.
  414. Uses BboxProcessor's label encoder if bbox_labels contain strings.
  415. """
  416. if len(bboxes) == 0 or self.bbox_labels is None:
  417. return None
  418. # Get label encoder from BboxProcessor if needed
  419. bbox_processor = self.get_processor("bboxes")
  420. if bbox_processor is None:
  421. return None
  422. if not all(isinstance(label, (int, float)) for label in self.bbox_labels):
  423. label_fields = bbox_processor.params.label_fields
  424. if label_fields is None:
  425. raise ValueError("BboxParams.label_fields must be specified when using string labels")
  426. first_class_label = label_fields[0]
  427. # Access encoder through label_manager's metadata
  428. metadata = bbox_processor.label_manager.metadata["bboxes"][first_class_label]
  429. if metadata.encoder is None:
  430. raise ValueError(f"No encoder found for label field {first_class_label}")
  431. target_labels = metadata.encoder.transform(self.bbox_labels)
  432. else:
  433. target_labels = np.array(self.bbox_labels)
  434. # Filter boxes by labels (usually in column 4)
  435. mask = np.isin(bboxes[:, 4], target_labels)
  436. filtered_boxes = bboxes[mask, :4]
  437. return filtered_boxes if len(filtered_boxes) > 0 else None
  438. def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
  439. """Get hole parameters based on either mask indices or bbox labels."""
  440. num_holes_per_obj = self.py_random.randint(*self.num_holes_range)
  441. if self.mask_indices is not None and "mask" in data:
  442. holes = fdropout.get_holes_from_mask(
  443. data["mask"],
  444. num_holes_per_obj,
  445. self.mask_indices,
  446. self.hole_height_range,
  447. self.hole_width_range,
  448. self.random_generator,
  449. )
  450. elif self.bbox_labels is not None and "bboxes" in data:
  451. target_boxes = self.get_boxes_from_bboxes(data["bboxes"])
  452. if target_boxes is None:
  453. holes = np.array([], dtype=np.int32).reshape((0, 4))
  454. else:
  455. target_boxes = denormalize_bboxes(target_boxes, data["image"].shape[:2])
  456. holes = fdropout.get_holes_from_boxes(
  457. target_boxes,
  458. num_holes_per_obj,
  459. self.hole_height_range,
  460. self.hole_width_range,
  461. self.random_generator,
  462. )
  463. else:
  464. warn("Neither valid mask nor bboxes provided, do not apply Constrained Coarse Dropout", stacklevel=2)
  465. holes = np.array([], dtype=np.int32).reshape((0, 4))
  466. return {
  467. "holes": holes,
  468. "seed": self.random_generator.integers(0, 2**32 - 1),
  469. }