Skip to content

Prevent overflow and precision loss when reducing by large factors - #10731

Open
lazerg wants to merge 1 commit into
python-pillow:mainfrom
lazerg:fix/reduce-overflow
Open

lazerg wants to merge 1 commit into
python-pillow:mainfrom
lazerg:fix/reduce-overflow

Conversation

@lazerg

@lazerg lazerg commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #10730

The general reduce paths (1xN, Nx1, NxN and the last row/column) divided with a fixed point multiplier of 2**24 / (xscale * yscale), truncated to an integer. That loses precision well before the factors in the issue: a white image reduced by 300 already comes back as 254, and by 1000 a 200 pixel comes back as 191. From 2897 the multiplier drops to 1, from 4096 256 * N wraps, and a bit above that the UINT32 sums overflow too.

This sums into uint64_t and divides by the scale directly, with the existing amend for rounding. Only these general paths change, the fixed size versions (1x2 up to 5x5) are unchanged, and I didn't see a speed difference for the general ones. The I, I;16 and F versions now compute the scale in double, so the products from the sanitizer output no longer overflow int.

@lazerg

lazerg commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

The ubuntu-latest Python pypy3.12 failure (Tests/test_features.py::test_version) also happens on main. It is not caused by this change.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

reduce() returns wrong pixel values for factors above 2896 because of integer overflow

1 participant