Skip to content

Conversation

@MalyalaKarthik66
Copy link
Contributor

This PR adds keras.layers.RandomResizedCrop, a preprocessing layer that
randomly crops and resizes images to a fixed target size.

The layer:

  • samples random crop area and aspect ratio during training
  • applies a deterministic center crop during inference
  • supports batched image inputs across all backends

This implementation supports image tensors only. For bounding boxes and
segmentation masks, users can rely on keras_cv.layers.RandomResizedCrop.

Closes #21822

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @MalyalaKarthik66, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances Keras's image preprocessing capabilities by adding the RandomResizedCrop layer. This layer is a powerful data augmentation tool that randomly crops and resizes images to a target size during training, effectively combining random cropping, zooming, and resizing. For inference, it performs a standard center crop and resize, ensuring predictable output. This addition provides a robust and efficient way to augment image datasets, crucial for improving the generalization and performance of vision models.

Highlights

  • New Preprocessing Layer: Introduced keras.layers.RandomResizedCrop, a new preprocessing layer for image data augmentation.
  • Training vs. Inference Behavior: The layer samples random crop area and aspect ratio during training, while applying a deterministic center crop during inference to ensure consistent results.
  • Backend and Input Support: The implementation supports batched image inputs across all Keras backends and is designed specifically for image tensors.
  • Comprehensive Testing: A dedicated test suite has been added to verify the layer's functionality, including randomness, determinism, output shape, seed reproducibility, and serialization.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces the RandomResizedCrop layer, a valuable addition for image data augmentation. The implementation is well-structured and includes a comprehensive test suite. I've identified a correctness issue in the handling of integer seeds which could lead to correlated random numbers where they should be independent. Additionally, I've suggested a refactoring for the compute_output_shape method to improve its clarity and robustness. Overall, this is a great contribution.

Comment on lines +125 to +126
if seed is None:
seed = self.generator
Copy link
Contributor

Choose a reason for hiding this comment

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

high

When an integer seed is provided, it is used for multiple separate random sampling operations (target_area, aspect_ratio, h_start, w_start). This will cause these operations to produce the same random value, which is incorrect as they should be independent. To fix this, when an integer seed is provided, it should be used to create a SeedGenerator instance, which will then provide a new seed for each random operation.

Suggested change
if seed is None:
seed = self.generator
if isinstance(seed, int):
seed = SeedGenerator(seed)
elif seed is None:
seed = self.generator

Comment on lines 200 to 214
input_shape = list(input_shape)
if self.data_format == "channels_last":
if len(input_shape) == 4:
input_shape[1] = self.height
input_shape[2] = self.width
else:
input_shape[0] = self.height
input_shape[1] = self.width
else:
if len(input_shape) == 4:
input_shape[2] = self.height
input_shape[3] = self.width
else:
input_shape[1] = self.height
input_shape[2] = self.width
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This implementation of compute_output_shape can be simplified and made more robust by using self.height_axis and self.width_axis, which are already defined in __init__. This avoids hardcoding indices based on tensor rank and data_format, making the code more consistent with get_random_transformation.

        input_shape = list(input_shape)
        input_shape[self.height_axis] = self.height
        input_shape[self.width_axis] = self.width

@codecov-commenter
Copy link

codecov-commenter commented Dec 16, 2025

Codecov Report

❌ Patch coverage is 83.33333% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.17%. Comparing base (71f4997) to head (82dfad2).

Files with missing lines Patch % Lines
...cessing/image_preprocessing/random_resized_crop.py 83.14% 9 Missing and 6 partials ⚠️

❗ There is a different number of reports uploaded between BASE (71f4997) and HEAD (82dfad2). Click for more details.

HEAD has 2 uploads less than BASE
Flag BASE (71f4997) HEAD (82dfad2)
keras 5 4
keras-torch 1 0
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #21929      +/-   ##
==========================================
- Coverage   82.63%   77.17%   -5.47%     
==========================================
  Files         581      582       +1     
  Lines       60435    60525      +90     
  Branches     9482     9491       +9     
==========================================
- Hits        49939    46708    -3231     
- Misses       8054    11437    +3383     
+ Partials     2442     2380      -62     
Flag Coverage Δ
keras 77.07% <83.33%> (-5.38%) ⬇️
keras-jax 62.02% <83.33%> (+0.03%) ⬆️
keras-numpy 57.25% <83.33%> (+0.03%) ⬆️
keras-openvino 37.31% <18.88%> (-0.03%) ⬇️
keras-tensorflow 64.20% <83.33%> (+0.02%) ⬆️
keras-torch ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add RandomResizedCrop

3 participants