Skip to content

Fix center_crop odd-padding placement to match the torchvision backend - #50592

Closed
InesZenkri wants to merge 1 commit into
huggingface:mainfrom
InesZenkri:fix-center-crop-odd-padding
Closed

InesZenkri wants to merge 1 commit into
huggingface:mainfrom
InesZenkri:fix-center-crop-odd-padding

Conversation

@InesZenkri

@InesZenkri InesZenkri commented Nov 10, 2026 •

Copy link
Copy Markdown

🤗 Transformers CI

Fixes #50584.

Here is my suggested fix: align image_transforms.center_crop (the numpy/PIL backend) with the torchvision convention when a crop has to pad an undersized image - the extra pixel of an odd difference now goes on the bottom/right instead of the top/left.

Two changes in center_crop:

  • pad with floor division on top/left (was ceil, which placed the extra pixel top/left);
  • compute the crop offsets relative to the padded canvas (they were computed against the original size, which only worked because ceil compensated).

Note that the direction is my proposal - changing the numpy/PIL backend rather than the torchvision one - since the backend split aims for torchvision parity. Happy to flip it if you'd rather keep the numpy convention. Only inputs smaller than the crop size by an odd number of pixels change; even padding and plain crops are untouched.

Tests

  • New test_center_crop_odd_padding_matches_torchvision: exact array equality with torchvision for an odd padding difference, both channel layouts.
  • pytest tests/test_image_transforms.py: 28 passed locally (Python 3.12, torch 2.14.1+cpu).

When a crop pads an undersized image by an odd number of pixels,
image_transforms.center_crop placed the extra pixel on the top/left
(ceil), while TorchvisionBackend.center_crop places it on the
bottom/right. Pad with floor division and compute the crop offsets
relative to the padded canvas, so both backends produce identical
output.

Adds a parity test against torchvision for both channel layouts.

Fixes huggingface#50584
@github-actions

Copy link
Copy Markdown
Contributor

Thank you for your contribution 🤗!

CI Security Gate — waiting for maintainer approval

CI is approved automatically only for authors who already have a contribution merged in this repository. A maintainer will review this PR and approve CI to run on it.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

center_crop pads the odd leftover pixel on opposite sides in the torchvision vs numpy/PIL backends

2 participants