Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions keras/src/layers/preprocessing/image_preprocessing/aug_mix.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,28 @@ class AugMix(BaseImagePreprocessingLayer):
interpolation: The interpolation method to use for resizing operations.
Options include `"nearest"`, `"bilinear"`. Default is `"bilinear"`.
seed: Integer. Used to create a random seed.

Example:

```python
# Create an AugMix layer
augmix = keras.layers.AugMix(
value_range=(0, 255),
num_chains=3, # Creates 3 different augmentation chains
chain_depth=3, # Each chain applies up to 3 random augmentations
factor=0.3, # Controls the strength of augmentations
all_ops=True
)

# Sample images
images = np.random.randint(0, 255, (8, 224, 224, 3), dtype='uint8')

# Each image is augmented in 3 different ways (chains) and then mixed
augmented_images = augmix(images, training=True)

# At inference, no augmentation is applied
output = augmix(images, training=False)
Comment on lines +78 to +94
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create an AugMix layer
augmix = keras.layers.AugMix(
    value_range=(0, 255),
    num_chains=3,  # Creates 3 different augmentation chains
    chain_depth=3, # Each chain applies up to 3 random augmentations
    factor=0.3,    # Controls the strength of augmentations
    all_ops=True
)

# Sample images
images = np.random.randint(0, 255, (8, 224, 224, 3), dtype='uint8')

# Each image is augmented in 3 different ways (chains) and then mixed
augmented_images = augmix(images, training=True)

# At inference, no augmentation is applied
output = augmix(images, training=False)

```
"""

_USE_BASE_FACTOR = False
Expand Down
27 changes: 27 additions & 0 deletions keras/src/layers/preprocessing/image_preprocessing/cut_mix.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,33 @@ class CutMix(BaseImagePreprocessingLayer):
in patch sizes, leading to more diverse and larger mixed patches.
Defaults to 1.
seed: Integer. Used to create a random seed.
Example:
```python
# Create a CutMix layer in which factor controls the patch size variability
cutmix = keras.layers.CutMix(factor=0.8)
# Generate sample images and one-hot encoded labels
images = np.random.randint(0, 255, (8, 224, 224, 3), dtype='uint8')
labels = keras.ops.one_hot(
np.array([0, 1, 2, 3, 0, 1, 2, 3]),
num_classes=4
)
# Random rectangular patches are cut from one image and pasted into another
# Labels are also mixed proportionally to the patch area
output = cutmix(
{"images": images, "labels": labels},
training=True
)
# At inference, no augmentation is applied
output_inference = cutmix(
{"images": images, "labels": labels},
training=False
)
Comment on lines +36 to +57
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create a CutMix layer in which factor controls the patch size variability
cutmix = keras.layers.CutMix(factor=0.8)

# Generate sample images and one-hot encoded labels
images = np.random.randint(0, 255, (8, 224, 224, 3), dtype='uint8')
labels = keras.ops.one_hot(
    np.array([0, 1, 2, 3, 0, 1, 2, 3]),
    num_classes=4
)

# Random rectangular patches are cut from one image and pasted into another
# Labels are also mixed proportionally to the patch area
output = cutmix(
    {"images": images, "labels": labels},
    training=True
)

# At inference, no augmentation is applied
output_inference = cutmix(
    {"images": images, "labels": labels},
    training=False
)

```
"""

_USE_BASE_FACTOR = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,29 @@ class MaxNumBoundingBoxes(BaseImagePreprocessingLayer):
max_number: Desired output number of bounding boxes.
padding_value: The padding value of the `boxes` and `labels` in
`bounding_boxes`. Defaults to `-1`.

Example:

```python
# Create a MaxNumBoundingBoxes layer to ensure max 10 boxes
max_boxes_layer = keras.layers.MaxNumBoundingBoxes(
max_number=10,
fill_value=-1
)

# Sample bounding boxes dict
bounding_boxes = {
"boxes": np.array([
[[10, 20, 100, 150], [50, 60, 200, 250], [0, 0, 50, 50]],
]),
"labels": np.array([[1, 2, 3]])
}

# Ensure max 10 boxes per image
# If fewer than 10 boxes, pad with fill_value (-1)
# If more than 10 boxes, truncate to 10
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you make these comments a paragraph?

result = max_boxes_layer({"bounding_boxes": bounding_boxes})
Comment on lines +22 to +39
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create a MaxNumBoundingBoxes layer to ensure max 10 boxes
max_boxes_layer = keras.layers.MaxNumBoundingBoxes(
    max_number=10,
    fill_value=-1
)

# Sample bounding boxes dict
bounding_boxes = {
    "boxes": np.array([
        [[10, 20, 100, 150], [50, 60, 200, 250], [0, 0, 50, 50]],
    ]),
    "labels": np.array([[1, 2, 3]])
}

# Ensure max 10 boxes per image
# If fewer than 10 boxes, pad with fill_value (-1)
# If more than 10 boxes, truncate to 10
result = max_boxes_layer({"bounding_boxes": bounding_boxes})

```
"""

def __init__(self, max_number, fill_value=-1, **kwargs):
Expand Down
20 changes: 20 additions & 0 deletions keras/src/layers/preprocessing/image_preprocessing/rand_augment.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,26 @@ class RandAugment(BaseImagePreprocessingLayer):
interpolation: The interpolation method to use for resizing operations.
Options include `nearest`, `bilinear`. Default is `bilinear`.
seed: Integer. Used to create a random seed.

Example:

```python
(images, labels), _ = keras.datasets.cifar10.load_data()
images = images.astype("float32")

# Create a RandAugment layer
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make the examples more concise, we can remove comments if the code is clear. For example, here the comment doesn't add much value as it's already clear what the code is doing.

augmenter = keras.layers.RandAugment(
value_range=(0, 255),
num_ops=2, # Apply 2 random augmentation operations per image
factor=0.5 # Control the strength of augmentations (0-1 normalized)
)

# Apply augmentation during training
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here regarding comment

augmented_images = augmenter(images, training=True)

# At inference time, no augmentation is applied
output = augmenter(images, training=False)
Comment on lines +39 to +53
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary import for keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the import.

import keras

(images, labels), _ = keras.datasets.cifar10.load_data()
images = images.astype("float32")

# Create a RandAugment layer
augmenter = keras.layers.RandAugment(
    value_range=(0, 255),
    num_ops=2,  # Apply 2 random augmentation operations per image
    factor=0.5  # Control the strength of augmentations (0-1 normalized)
)

# Apply augmentation during training
augmented_images = augmenter(images, training=True)

# At inference time, no augmentation is applied
output = augmenter(images, training=False)

```
"""

_USE_BASE_FACTOR = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,24 @@ class RandomColorDegeneration(BaseImagePreprocessingLayer):
passed float is sampled. In order to ensure the value is always the
same, please pass a tuple with two identical floats: `(0.5, 0.5)`.
seed: Integer. Used to create a random seed.
Example:
```python
# Create a RandomColorDegeneration layer
color_degeneration = keras.layers.RandomColorDegeneration(
factor=0.4,
value_range=(0, 255)
)
images = np.random.randint(0, 255, (2, 224, 224, 3), dtype='uint8')
# Apply color degeneration during training
degraded_images = color_degeneration(images, training=True)
# At inference time, no degradation is applied
output = color_degeneration(images, training=False)
Comment on lines +36 to +48
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create a RandomColorDegeneration layer
color_degeneration = keras.layers.RandomColorDegeneration(
    factor=0.4,
    value_range=(0, 255)
)

images = np.random.randint(0, 255, (2, 224, 224, 3), dtype='uint8')

# Apply color degeneration during training
degraded_images = color_degeneration(images, training=True)

# At inference time, no degradation is applied
output = color_degeneration(images, training=False)

```
"""

_VALUE_RANGE_VALIDATION_ERROR = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,27 @@ class RandomColorJitter(BaseImagePreprocessingLayer):
always the same, please pass a tuple with two identical
floats: `(0.5, 0.5)`.
seed: Integer. Used to create a random seed.

Example:

```python
(images, labels), _ = keras.datasets.cifar10.load_data()
images = images.astype("float32")

# Create a RandomColorJitter layer
jitter = keras.layers.RandomColorJitter(
value_range=(0, 255),
brightness_factor=0.2, # ±20% brightness change
contrast_factor=0.5, # contrast factor between 0.5 and 1.5
saturation_factor=0.4, # saturation factor between 0.0 and 0.4
hue_factor=0.2
)
# All 4 color adjustments are applied sequentially and randomly
jittered_images = jitter(images, training=True)

# At inference time, no jittering is applied
output = jitter(images, training=False)
Comment on lines +67 to +82
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary import for keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the import.

import keras

(images, labels), _ = keras.datasets.cifar10.load_data()
images = images.astype("float32")

# Create a RandomColorJitter layer
jitter = keras.layers.RandomColorJitter(
    value_range=(0, 255),
    brightness_factor=0.2,  # ±20% brightness change
    contrast_factor=0.5,    # contrast factor between 0.5 and 1.5
    saturation_factor=0.4,  # saturation factor between 0.0 and 0.4
    hue_factor=0.2
)
# All 4 color adjustments are applied sequentially and randomly
jittered_images = jitter(images, training=True)

# At inference time, no jittering is applied
output = jitter(images, training=False)

```
"""

def __init__(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@ class RandomContrast(BaseImagePreprocessingLayer):
typically either `[0, 1]` or `[0, 255]` depending on how your
preprocessing pipeline is set up.
seed: Integer. Used to create a random seed.

Example:

```python
# Create a RandomContrast layer
contrast_layer = keras.layers.RandomContrast(
factor=0.3,
value_range=(0, 255)
)

images = np.random.randint(0, 255, (2, 224, 224, 3), dtype='uint8')

contrasted_images = contrast_layer(images, training=True)

# At inference time, no adjustment is applied
output = contrast_layer(images, training=False)
Comment on lines +52 to +63
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create a RandomContrast layer
contrast_layer = keras.layers.RandomContrast(
    factor=0.3,
    value_range=(0, 255)
)

images = np.random.randint(0, 255, (2, 224, 224, 3), dtype='uint8')

contrasted_images = contrast_layer(images, training=True)

# At inference time, no adjustment is applied
output = contrast_layer(images, training=False)

```
"""

_FACTOR_BOUNDS = (0, 1)
Expand Down
17 changes: 17 additions & 0 deletions keras/src/layers/preprocessing/image_preprocessing/random_crop.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ class RandomCrop(BaseImagePreprocessingLayer):
seed: Integer. Used to create a random seed.
**kwargs: Base layer keyword arguments, such as
`name` and `dtype`.

Example:

```python
# Create a RandomCrop layer that outputs 192x192 images
crop_layer = keras.layers.RandomCrop(height=192, width=192)

# Generate sample images (batch_size=2, height=224, width=224, channels=3)
images = np.random.randint(0, 255, (2, 224, 224, 3), dtype='uint8')

# Apply random cropping during training
cropped_images = crop_layer(images, training=True)
# Output shape: (2, 192, 192, 3)

# At inference time, performs center crop
center_cropped = crop_layer(images, training=False)
Comment on lines +54 to +65
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create a RandomCrop layer that outputs 192x192 images
crop_layer = keras.layers.RandomCrop(height=192, width=192)

# Generate sample images (batch_size=2, height=224, width=224, channels=3)
images = np.random.randint(0, 255, (2, 224, 224, 3), dtype='uint8')

# Apply random cropping during training
cropped_images = crop_layer(images, training=True)
# Output shape: (2, 192, 192, 3)

# At inference time, performs center crop
center_cropped = crop_layer(images, training=False)

```
"""

def __init__(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,30 @@ class RandomElasticTransform(BaseImagePreprocessingLayer):
preprocessing pipeline is set up.
seed: Integer. Used to create a random seed.

Example:

```python
# Create a RandomElasticTransform layer
# This creates wave-like distortions in the image
elastic_transform = keras.layers.RandomElasticTransform(
factor=1.0,
scale=(50, 100) # Control the magnitude of distortion
)

image = np.random.randint(0, 255, (224, 224, 3), dtype='uint8')

# Apply elastic deformation
# The image will appear warped/stretched like elastic material
output = elastic_transform(image, training=True)

# For more subtle distortions
subtle_elastic = keras.layers.RandomElasticTransform(
factor=0.5,
scale=(10, 30),
fill_mode="reflect"
)
subtle_output = subtle_elastic(image, training=True)
Comment on lines +68 to +87
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

# Create a RandomElasticTransform layer
# This creates wave-like distortions in the image
elastic_transform = keras.layers.RandomElasticTransform(
    factor=1.0,
    scale=(50, 100)  # Control the magnitude of distortion
)

image = np.random.randint(0, 255, (224, 224, 3), dtype='uint8')

# Apply elastic deformation
# The image will appear warped/stretched like elastic material
output = elastic_transform(image, training=True)

# For more subtle distortions
subtle_elastic = keras.layers.RandomElasticTransform(
    factor=0.5,
    scale=(10, 30),
    fill_mode="reflect"
)
subtle_output = subtle_elastic(image, training=True)

```
"""

_USE_BASE_FACTOR = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,27 @@ class RandomErasing(BaseImagePreprocessingLayer):
typically either `[0, 1]` or `[0, 255]` depending on how your
preprocessing pipeline is set up.
seed: Integer. Used to create a random seed.

Example:

```python
# Create a RandomErasing layer with default factor
random_erasing = keras.layers.RandomErasing(factor=1.0)

# Your input image
image = [...] # your input image
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to create random images similar to previous examples?


# Apply random erasing
output = random_erasing(image, training=True)

# For custom scale and fill value
random_erasing_custom = keras.layers.RandomErasing(
factor=0.5,
scale=(0.05, 0.2),
fill_value=128
)
output_custom = random_erasing_custom(image, training=True)
Comment on lines +48 to +63
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example uses a placeholder image = [...] which makes it not runnable. To improve the documentation, please provide a complete, runnable example. This can be done by creating a sample image tensor using numpy.

import numpy as np
import keras

# Create a RandomErasing layer with default factor
random_erasing = keras.layers.RandomErasing(factor=1.0)

# Your input image
image = np.random.randint(0, 255, (224, 224, 3), dtype='uint8')

# Apply random erasing
output = random_erasing(image, training=True)

# For custom scale and fill value
random_erasing_custom = keras.layers.RandomErasing(
    factor=0.5,
    scale=(0.05, 0.2),
    fill_value=128
)
output_custom = random_erasing_custom(image, training=True)

```
"""

_USE_BASE_FACTOR = False
Expand Down
10 changes: 10 additions & 0 deletions keras/src/layers/preprocessing/image_preprocessing/random_flip.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ class RandomFlip(BaseImagePreprocessingLayer):
seed: Integer. Used to create a random seed.
**kwargs: Base layer keyword arguments, such as
`name` and `dtype`.

Example:

```python
flip_layer = keras.layers.RandomFlip(mode="horizontal_and_vertical")

images = np.random.randint(0, 255, (4, 224, 224, 3), dtype='uint8')
# Random horizontal and vertical flip during training
output = flip_layer(images, training=True)
Comment on lines +53 to +57
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example is not runnable as it's missing the necessary imports for numpy and keras. To improve documentation quality and user experience, please make the example self-contained and runnable by adding the imports.

import numpy as np
import keras

flip_layer = keras.layers.RandomFlip(mode="horizontal_and_vertical")

images = np.random.randint(0, 255, (4, 224, 224, 3), dtype='uint8')
# Random horizontal and vertical flip during training
output = flip_layer(images, training=True)

```
"""

_USE_BASE_FACTOR = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,31 @@ class RandomGaussianBlur(BaseImagePreprocessingLayer):
typically either `[0, 1]` or `[0, 255]` depending on how your
preprocessing pipeline is set up.
seed: Integer. Used to create a random seed.

Example:

```python
# Create a RandomGaussianBlur layer
random_blur = keras.layers.RandomGaussianBlur(
factor=1.0,
kernel_size=3,
sigma=1.0
)

# Your input image
image = [...] # your input image

# Apply random Gaussian blur
output = random_blur(image, training=True)

# For stronger blur with custom sigma range
strong_blur = keras.layers.RandomGaussianBlur(
factor=1.0,
kernel_size=5,
sigma=(1.0, 3.0)
)
output_blurred = strong_blur(image, training=True)
Comment on lines +42 to +61
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example uses a placeholder image = [...] which makes it not runnable. To improve the documentation, please provide a complete, runnable example. This can be done by creating a sample image tensor using numpy.

import numpy as np
import keras

# Create a RandomGaussianBlur layer
random_blur = keras.layers.RandomGaussianBlur(
    factor=1.0,
    kernel_size=3,
    sigma=1.0
)

# Your input image
image = np.random.randint(0, 255, (224, 224, 3), dtype='uint8')

# Apply random Gaussian blur
output = random_blur(image, training=True)

# For stronger blur with custom sigma range
strong_blur = keras.layers.RandomGaussianBlur(
    factor=1.0,
    kernel_size=5,
    sigma=(1.0, 3.0)
)
output_blurred = strong_blur(image, training=True)

```
"""

_USE_BASE_FACTOR = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,23 @@ class RandomGrayscale(BaseImagePreprocessingLayer):
Same as input shape. The output maintains the same number of channels
as the input, even for grayscale-converted images where all channels
will have the same value.

Example:

```python
# Create a RandomGrayscale layer
random_grayscale = keras.layers.RandomGrayscale(factor=0.5)

# Your input image
image = [...] # your input image

# Apply random grayscale conversion
output = random_grayscale(image, training=True)

# For always converting to grayscale
grayscale_always = keras.layers.RandomGrayscale(factor=1.0)
output_grayscale = grayscale_always(image, training=True)
Comment on lines +50 to +61
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example uses a placeholder image = [...] which makes it not runnable. To improve the documentation, please provide a complete, runnable example. This can be done by creating a sample image tensor using numpy.

import numpy as np
import keras

# Create a RandomGrayscale layer
random_grayscale = keras.layers.RandomGrayscale(factor=0.5)

# Your input image
image = np.random.randint(0, 255, (224, 224, 3), dtype='uint8')

# Apply random grayscale conversion
output = random_grayscale(image, training=True)

# For always converting to grayscale
grayscale_always = keras.layers.RandomGrayscale(factor=1.0)
output_grayscale = grayscale_always(image, training=True)

```
"""

def __init__(self, factor=0.5, data_format=None, seed=None, **kwargs):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,26 @@ class RandomInvert(BaseImagePreprocessingLayer):
represents the upper bound. Images passed to the layer should have
values within `value_range`. Defaults to `(0, 255)`.
seed: Integer. Used to create a random seed.

Example:

```python
# Create a RandomInvert layer with default factor
random_invert = keras.layers.RandomInvert(factor=0.5)

# Your input image
image = [...] # your input image

# Apply random color inversion
output = random_invert(image, training=True)

# For always inverting colors with custom value range
invert_always = keras.layers.RandomInvert(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove always from the variable name?

factor=1.0,
value_range=[0.0, 1.0]
)
output_inverted = invert_always(image, training=True)
Comment on lines +37 to +51
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The code example uses a placeholder image = [...] which makes it not runnable. To improve the documentation, please provide a complete, runnable example. This can be done by creating a sample image tensor using numpy.

import numpy as np
import keras

# Create a RandomInvert layer with default factor
random_invert = keras.layers.RandomInvert(factor=0.5)

# Your input image
image = np.random.randint(0, 255, (224, 224, 3), dtype='uint8')

# Apply random color inversion
output = random_invert(image, training=True)

# For always inverting colors with custom value range
invert_always = keras.layers.RandomInvert(
    factor=1.0,
    value_range=[0.0, 1.0]
)
output_inverted = invert_always(image, training=True)

```
"""

_USE_BASE_FACTOR = False
Expand Down
Loading