Skip to content

Conversation

@utsab345
Copy link
Contributor

PR Description

This PR fixes the logic controlling crop_to_aspect_ratio inside transform_images() in the Resizing layer.

Summary of changes:

Ensures cropping only occurs when aspect ratios differ.

Adds a small epsilon (1e-6) for floating-point comparisons.

Fixes Ruff E501 long line comment warnings.

Verified that test_crop_to_aspect_ratio_no_op_when_aspects_match passes, confirming functional parity.

Related issue:

Fixes #21773

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @utsab345, 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 refines the image resizing and saving functionalities within the Keras utilities. The primary focus is on fixing a subtle bug in the Resizing layer where crop_to_aspect_ratio was sometimes incorrectly applied even when the image's aspect ratio already matched the target. This is resolved by introducing a more precise comparison using an epsilon. Additionally, the PR improves the save_img utility by standardizing JPG format handling and adds comprehensive tests for both the resizing logic and image saving, ensuring greater reliability and correctness.

Highlights

  • Resizing Layer Logic Fix: Corrected the logic within the transform_images() method of the Resizing layer to ensure that crop_to_aspect_ratio is only applied when the source and target aspect ratios genuinely differ. This prevents unnecessary cropping when aspect ratios already match.
  • Floating-Point Comparison Robustness: Introduced a small epsilon (1e-6) for floating-point comparisons when checking aspect ratios, improving the robustness and accuracy of the conditional cropping logic.
  • Linting Fixes: Addressed Ruff E501 warnings related to long lines in comments, improving code style and adherence to linting standards.
  • New Test for Cropping Logic: Added a new test case, test_crop_to_aspect_ratio_no_op_when_aspects_match, to explicitly verify that crop_to_aspect_ratio=True behaves identically to False when source and target aspect ratios are already the same.
  • Image Saving Improvements: Enhanced the save_img utility function by normalizing 'jpg' file format to 'jpeg' and adding a new integration test to cover JPG saving, including the conversion of RGBA images to RGB when saving as JPEG.
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 correctly refactors the crop_to_aspect_ratio logic in the Resizing layer to only trigger when aspect ratios differ, and also includes some linting fixes. My review focuses on improving robustness. I've suggested adding a check to prevent a potential ZeroDivisionError in resizing.py and fixing a bug in image_utils.py where a warning for RGBA to RGB conversion for JPEG images was missed when the file format was inferred from the path.

Comment on lines +107 to +108
source_aspect_ratio = input_width / input_height
target_aspect_ratio = self.width / self.height
Copy link
Contributor

Choose a reason for hiding this comment

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

high

To prevent a potential ZeroDivisionError if input_height or self.height is zero, it's safer to add a small epsilon to the denominators. This is a good defensive practice, especially since these values could be dynamic tensors.

Suggested change
source_aspect_ratio = input_width / input_height
target_aspect_ratio = self.width / self.height
source_aspect_ratio = input_width / (input_height + self.backend.epsilon())
target_aspect_ratio = self.width / (self.height + self.backend.epsilon())

Comment on lines 179 to 187
if file_format is not None and file_format.lower() == "jpg":
file_format = "jpeg"
img = array_to_img(x, data_format=data_format, scale=scale)
if img.mode == "RGBA" and (file_format == "jpg" or file_format == "jpeg"):
if img.mode == "RGBA" and file_format == "jpeg":
warnings.warn(
"The JPG format does not support RGBA images, converting to RGB."
"The JPEG format does not support RGBA images, converting to RGB."
)
img = img.convert("RGB")
img.save(path, format=file_format, **kwargs)
Copy link
Contributor

Choose a reason for hiding this comment

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

high

The current logic for warning about RGBA to RGB conversion for JPEG images has a flaw. It doesn't handle the case where file_format is None and the format is inferred from the file path (e.g., 'image.jpg'). In this scenario, PIL would convert the image silently, but no warning would be issued. The logic should be updated to infer the format from the path if it's not explicitly provided, ensuring the warning is always shown when appropriate.

    if file_format is None and isinstance(path, (str, bytes, pathlib.Path)):
        path_obj = pathlib.Path(path)
        if path_obj.suffix:
            file_format = path_obj.suffix[1:].lower()

    # Normalize jpg → jpeg
    if file_format is not None and file_format.lower() == "jpg":
        file_format = "jpeg"
    img = array_to_img(x, data_format=data_format, scale=scale)
    if img.mode == "RGBA" and file_format == "jpeg":
        warnings.warn(
            "The JPEG format does not support RGBA images, converting to RGB."
        )
        img = img.convert("RGB")
    img.save(path, format=file_format, **kwargs)

@codecov-commenter
Copy link

codecov-commenter commented Oct 25, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.64%. Comparing base (10b51ce) to head (6c3e069).

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #21779   +/-   ##
=======================================
  Coverage   82.63%   82.64%           
=======================================
  Files         577      577           
  Lines       59249    59254    +5     
  Branches     9291     9291           
=======================================
+ Hits        48963    48968    +5     
  Misses       7903     7903           
  Partials     2383     2383           
Flag Coverage Δ
keras 82.46% <100.00%> (+<0.01%) ⬆️
keras-jax 63.35% <100.00%> (+<0.01%) ⬆️
keras-numpy 57.57% <100.00%> (+<0.01%) ⬆️
keras-openvino 34.31% <0.00%> (-0.01%) ⬇️
keras-tensorflow 64.11% <100.00%> (+<0.01%) ⬆️
keras-torch 63.65% <100.00%> (+<0.01%) ⬆️

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.

Memory changed when changing the value of crop_to_aspect_ratio in case that this arg actually not work

3 participants