Skip to content

Commit

Permalink
Remove get_params_dependent_on_targets (#1857)
Browse files Browse the repository at this point in the history
* GridDistortion remove target_as_params

* Affine, PiecewiseAffine, remove targets_as_params

* Rotate - remove targets_as_params

* XYMasking remove targets_on_params

* MaskDropout - change get_params_dependent_on_targets to get_params_dependent_on_data

* GridDropout remove targets_as_params

* CoarseDropout remove targets_as_params

* GlassBlur remove targets_as_params

* ChannelDropout remove targets_as_params

* Crops - set get_params_dependent_on_data

* RandomGridShuffle remove targets_as_params

* RandomGravel remove
targets_as_params

* RandomRain, RandomFog remove targets_as_params

* RandomSunFlare, RandomShadow -remove targets_as_params

* RandomToneCurve remove targets_as_params

* GaussNoise remove targets_as_params

* ChannelShuffle remove targets_as_params

* MultiplicativeNoise remove targets_as_params

* TemplateTransform remove targets_as_params

* PixelDropout remove targets_as_params

* Spatter remove targets_as_params

* ChannelDropout fix num_channels

* RandomToneCurve fix num_channels

* MultiplicativeNoise fix num_channels

* GaussNoise fix shape / ndim
  • Loading branch information
ayasyrev authored Jul 26, 2024
1 parent 8d5c775 commit 2af5cde
Show file tree
Hide file tree
Showing 11 changed files with 150 additions and 202 deletions.
10 changes: 2 additions & 8 deletions albumentations/augmentations/blur/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,10 +328,8 @@ def apply(self, img: np.ndarray, *args: Any, dxy: np.ndarray, **params: Any) ->

return fblur.glass_blur(img, self.sigma, self.max_delta, self.iterations, dxy, self.mode)

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, np.ndarray]:
img = params["image"]

height, width = img.shape[:2]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, np.ndarray]:
height, width = params["shape"][:2]

# generate array containing all necessary values for transformations
width_pixels = height - self.max_delta * 2
Expand All @@ -344,10 +342,6 @@ def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, n
def get_transform_init_args_names(self) -> tuple[str, str, str, str]:
return ("sigma", "max_delta", "iterations", "mode")

@property
def targets_as_params(self) -> list[str]:
return ["image"]


class AdvancedBlur(ImageOnlyTransform):
"""Blurs the input image using a Generalized Normal filter with randomly selected parameters.
Expand Down
90 changes: 54 additions & 36 deletions albumentations/augmentations/crops/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,6 @@ def apply(self, img: np.ndarray, crop_coords: tuple[int, int, int, int], **param
y_max = crop_coords[3]
return fcrops.crop(img, x_min=x_min, y_min=y_min, x_max=x_max, y_max=y_max)

@property
def targets_as_params(self) -> list[str]:
return ["image"]

def apply_to_bbox(
self,
bbox: BoxInternalType,
Expand Down Expand Up @@ -122,15 +118,19 @@ def __init__(self, height: int, width: int, p: float = 1.0, always_apply: bool |
self.height = height
self.width = width

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
img = params["image"]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
shape = params["shape"]

image_height, image_width = img.shape[:2]
image_height, image_width = shape[:2]

if self.height > image_height or self.width > image_width:
raise CropSizeError(
f"Crop size (height, width) exceeds image dimensions (height, width):"
f" {(self.height, self.width)} vs {img.shape[:2]}",
f" {(self.height, self.width)} vs {shape[:2]}",
)

h_start = random.random()
Expand Down Expand Up @@ -169,10 +169,12 @@ def __init__(self, height: int, width: int, p: float = 1.0, always_apply: bool |
def get_transform_init_args_names(self) -> tuple[str, ...]:
return "height", "width"

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
img = params["image"]

image_height, image_width = img.shape[:2]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
image_height, image_width = params["shape"][:2]
crop_coords = fcrops.get_center_crop_coords(image_height, image_width, self.height, self.width)

return {"crop_coords": crop_coords}
Expand Down Expand Up @@ -230,7 +232,11 @@ def __init__(
def get_transform_init_args_names(self) -> tuple[str, ...]:
return "x_min", "y_min", "x_max", "y_max"

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
return {"crop_coords": (self.x_min, self.y_min, self.x_max, self.y_max)}


Expand Down Expand Up @@ -330,9 +336,6 @@ def update_params(self, params: dict[str, Any], **kwargs: Any) -> dict[str, Any]
params["crop_coords"] = crop_coords
return params

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, int | float]:
return params

def get_transform_init_args_names(self) -> tuple[str, ...]:
return "height", "width", "ignore_values", "ignore_channels"

Expand Down Expand Up @@ -375,10 +378,6 @@ def apply(
crop = fcrops.crop(img, *crop_coords)
return fgeometric.resize(crop, self.size[0], self.size[1], interpolation)

@property
def targets_as_params(self) -> list[str]:
return ["image"]

def apply_to_bbox(
self,
bbox: BoxInternalType,
Expand Down Expand Up @@ -478,8 +477,12 @@ def __init__(
self.min_max_height = min_max_height
self.w2h_ratio = w2h_ratio

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
image_height, image_width = params["image"].shape[:2]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
image_height, image_width = params["shape"][:2]

crop_height = random.randint(self.min_max_height[0], self.min_max_height[1])
crop_width = int(crop_height * self.w2h_ratio)
Expand Down Expand Up @@ -569,9 +572,12 @@ def __init__(
self.scale = scale
self.ratio = ratio

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
img = params["image"]
image_height, image_width = img.shape[:2]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
image_height, image_width = params["shape"][:2]
area = image_height * image_width

for _ in range(10):
Expand Down Expand Up @@ -684,10 +690,14 @@ def _clip_bbox(bbox: BoxInternalType, height: int, width: int) -> BoxInternalTyp
y_max = np.clip(y_max, y_min, height)
return x_min, y_min, x_max, y_max

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[float, ...]]:
bbox = params[self.cropping_bbox_key]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[float, ...]]:
bbox = data[self.cropping_bbox_key]

height, width = params["image"].shape[:2]
height, width = params["shape"][:2]

bbox = self._clip_bbox(bbox, height, width)

Expand All @@ -709,7 +719,7 @@ def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, t

@property
def targets_as_params(self) -> list[str]:
return ["image", self.cropping_bbox_key]
return [self.cropping_bbox_key]

def get_transform_init_args_names(self) -> tuple[str, ...]:
return "max_part_shift", "cropping_bbox_key"
Expand Down Expand Up @@ -756,14 +766,18 @@ def _get_coords_no_bbox(self, image_height: int, image_width: int) -> tuple[int,

return fcrops.get_crop_coords(image_height, image_width, crop_height, crop_width, h_start, w_start)

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
image_height, image_width = params["image"].shape[:2]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
image_height, image_width = params["shape"][:2]

if len(params["bboxes"]) == 0: # less likely, this class is for use with bboxes.
if len(data["bboxes"]) == 0: # less likely, this class is for use with bboxes.
crop_coords = self._get_coords_no_bbox(image_height, image_width)
return {"crop_coords": crop_coords}

bbox_union = union_of_bboxes(bboxes=params["bboxes"], erosion_rate=self.erosion_rate)
bbox_union = union_of_bboxes(bboxes=data["bboxes"], erosion_rate=self.erosion_rate)

if bbox_union is None:
crop_coords = self._get_coords_no_bbox(image_height, image_width)
Expand All @@ -788,7 +802,7 @@ def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, t

@property
def targets_as_params(self) -> list[str]:
return ["image", "bboxes"]
return ["bboxes"]

def get_transform_init_args_names(self) -> tuple[str, ...]:
return ("erosion_rate",)
Expand Down Expand Up @@ -1335,8 +1349,12 @@ def __init__(
self.crop_top = crop_top
self.crop_bottom = crop_bottom

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, tuple[int, int, int, int]]:
height, width = params["image"].shape[:2]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, tuple[int, int, int, int]]:
height, width = params["shape"][:2]

x_min = random.randint(0, int(self.crop_left * width))
x_max = random.randint(max(x_min + 1, int((1 - self.crop_right) * width)), width)
Expand Down
14 changes: 5 additions & 9 deletions albumentations/augmentations/dropout/channel_dropout.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
import random
from typing import Any, Mapping

from albucore.utils import is_grayscale_image
from typing_extensions import Annotated

from albucore import get_num_channels
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform

from .functional import channel_dropout
Expand Down Expand Up @@ -57,11 +57,11 @@ def __init__(
def apply(self, img: np.ndarray, channels_to_drop: tuple[int, ...], **params: Any) -> np.ndarray:
return channel_dropout(img, channels_to_drop, self.fill_value)

def get_params_dependent_on_targets(self, params: Mapping[str, Any]) -> dict[str, Any]:
img = params["image"]
num_channels = img.shape[-1]
def get_params_dependent_on_data(self, params: Mapping[str, Any], data: Mapping[str, Any]) -> dict[str, Any]:
image = data["image"] if "image" in data else data["images"][0]
num_channels = get_num_channels(image)

if is_grayscale_image(img):
if num_channels == 1:
msg = "Images has one channel. ChannelDropout is not defined."
raise NotImplementedError(msg)

Expand All @@ -77,7 +77,3 @@ def get_params_dependent_on_targets(self, params: Mapping[str, Any]) -> dict[str

def get_transform_init_args_names(self) -> tuple[str, ...]:
return "channel_drop_range", "fill_value"

@property
def targets_as_params(self) -> list[str]:
return ["image"]
9 changes: 2 additions & 7 deletions albumentations/augmentations/dropout/coarse_dropout.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,8 @@ def calculate_hole_dimensions(
hole_width = int(width * random.uniform(width_range[0], width_range[1]))
return hole_height, hole_width

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, Any]:
img = params["image"]
height, width = img.shape[:2]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
height, width = params["shape"][:2]

holes = []
num_holes = random.randint(self.num_holes_range[0], self.num_holes_range[1])
Expand All @@ -246,10 +245,6 @@ def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, A

return {"holes": holes}

@property
def targets_as_params(self) -> list[str]:
return ["image"]

def apply_to_keypoints(
self,
keypoints: Sequence[KeypointType],
Expand Down
9 changes: 2 additions & 7 deletions albumentations/augmentations/dropout/grid_dropout.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,8 @@ def apply_to_mask(

return fdropout.cutout(mask, holes, self.mask_fill_value)

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, Any]:
img = params["image"]
height, width = img.shape[:2]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
height, width = params["shape"][:2]
unit_width, unit_height = self._calculate_unit_dimensions(width, height)
hole_width, hole_height = self._calculate_hole_dimensions(unit_width, unit_height)
shift_x, shift_y = self._calculate_shifts(unit_width, unit_height, hole_width, hole_height)
Expand Down Expand Up @@ -244,10 +243,6 @@ def _generate_holes(
holes.append((x1, y1, x2, y2))
return holes

@property
def targets_as_params(self) -> list[str]:
return ["image"]

def get_transform_init_args_names(self) -> tuple[str, ...]:
return (
"ratio",
Expand Down
5 changes: 2 additions & 3 deletions albumentations/augmentations/dropout/mask_dropout.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def __init__(
def targets_as_params(self) -> list[str]:
return ["mask"]

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, Any]:
mask = params["mask"]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
mask = data["mask"]

label_image, num_labels = label(mask, return_num=True)

Expand All @@ -93,7 +93,6 @@ def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, A
dropout_mask |= label_image == label_index

params.update({"dropout_mask": dropout_mask})
del params["mask"]
return params

def apply(self, img: np.ndarray, dropout_mask: np.ndarray, **params: Any) -> np.ndarray:
Expand Down
13 changes: 6 additions & 7 deletions albumentations/augmentations/dropout/xy_masking.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,12 @@ def validate_mask_length(
elif mask_length < 0 or mask_length > dimension_size:
raise ValueError(f"{dimension_name} {mask_length} exceeds image {dimension_name} {dimension_size}")

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, list[tuple[int, int, int, int]]]:
img = params["image"]
height, width = img.shape[:2]
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, list[tuple[int, int, int, int]]]:
height, width = params["shape"][:2]

# Use the helper method to validate mask lengths against image dimensions
self.validate_mask_length(self.mask_x_length, width, "mask_x_length")
Expand Down Expand Up @@ -190,10 +193,6 @@ def generate_masks(
masks.append((x1, y1, x2, y2))
return masks

@property
def targets_as_params(self) -> list[str]:
return ["image"]

def apply_to_keypoints(
self,
keypoints: Sequence[KeypointType],
Expand Down
8 changes: 2 additions & 6 deletions albumentations/augmentations/geometric/rotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,14 +233,10 @@ def _rotated_rect_with_max_area(height: int, width: int, angle: float) -> dict[s
"y_max": min(height, int(height / 2 + hr / 2)),
}

@property
def targets_as_params(self) -> list[str]:
return ["image"]

def get_params_dependent_on_targets(self, params: dict[str, Any]) -> dict[str, Any]:
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
out_params = {"angle": random.uniform(self.limit[0], self.limit[1])}
if self.crop_border:
height, width = params["image"].shape[:2]
height, width = params["shape"][:2]
out_params.update(self._rotated_rect_with_max_area(height, width, out_params["angle"]))
else:
out_params.update({"x_min": -1, "x_max": -1, "y_min": -1, "y_max": -1})
Expand Down
Loading

0 comments on commit 2af5cde

Please sign in to comment.