Skip to content

FIX reconstruct_from_patches_2d when patch size equals image size#33643

Merged
jeremiedbb merged 3 commits intoscikit-learn:mainfrom
EdenRochmanSharabi:fix/reconstruct-patches-2d
Apr 9, 2026
Merged

FIX reconstruct_from_patches_2d when patch size equals image size#33643
jeremiedbb merged 3 commits intoscikit-learn:mainfrom
EdenRochmanSharabi:fix/reconstruct-patches-2d

Conversation

@EdenRochmanSharabi
Copy link
Copy Markdown
Contributor

Summary

Fixes #10910

reconstruct_from_patches_2d produces incorrect results when one patch
dimension equals the corresponding image dimension (e.g. patches of size
128x128 from a 128x256 image). The reconstruction error is ~1.0 instead of
~0.0.

Root cause

The overlap counting formula on line 524:

min(i + 1, p_h, i_h - i) * min(j + 1, p_w, i_w - j)

uses p_h and p_w (patch dimensions) as upper bounds. But when
p_h == i_h, there is only n_h = 1 patch along that axis, so every pixel
has an overlap count of 1. The formula incorrectly computes values up to
p_h (128), dividing pixel values by 128 instead of 1.

Fix

Add n_h and n_w (number of patches per axis) to the min() call:

min(i + 1, p_h, n_h, i_h - i) * min(j + 1, p_w, n_w, i_w - j)

This correctly constrains the overlap count when the number of patches is
smaller than the patch size. For the normal case (p_h << i_h), n_h is
large and doesn't affect the result.

Changes

  • sklearn/feature_extraction/image.py: Added n_h and n_w to the
    overlap count formula.
  • sklearn/feature_extraction/tests/test_image.py: Added parametrized
    non-regression test covering p_h == i_h, p_w == i_w, p == img, and
    the RGB variant.
  • Changelog entry added.

Eden Rochman added 2 commits March 26, 2026 21:22
The overlap counting formula used p_h and p_w (patch dimensions) as
upper bounds, but when a patch dimension equals the image dimension
there is only one patch along that axis (n_h=1 or n_w=1). The correct
upper bound must also include n_h and n_w (the number of patches along
each axis), otherwise pixels are divided by inflated overlap counts.

Add n_h and n_w to the min() call in the overlap computation.

Fixes scikit-learn#10910
Copy link
Copy Markdown
Member

@jeremiedbb jeremiedbb left a comment

Choose a reason for hiding this comment

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

LGTM. Thanks

@jeremiedbb jeremiedbb enabled auto-merge (squash) April 9, 2026 15:50
@jeremiedbb jeremiedbb merged commit d9a1b74 into scikit-learn:main Apr 9, 2026
38 checks passed
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.

Bug function: reconstruct_from_patches_2d

2 participants