Repository navigation
Compute resize_with_pad sizes exactly instead of in float32 - #129784
copybara-service[bot] merged 3 commits into
Conversation
`resize_with_pad` scales the image by min(target_width / width, target_height / height) and pads the rest. It computed that scale in float32, then took `floor(height / ratio)`. When the scaled size is a whole number, float32 often lands just below it, so the floor drops a row or column: the image is resized one pixel short and padded with a line of zeros. For example 512x512 to 224x224 gives a 223x223 image with a black border, and 480x640 to 300x300 gets a black right-hand column. The padding computed from the same float can also be one less than intended, shifting the image off center. Compute the resized size as min(target, size * other_target // other_size) and the padding as floor((target - scaled size) / 2) with int64 arithmetic. These are the same formulas as before, evaluated exactly; on 200,000 random size combinations they match exact rational arithmetic everywhere, while the float32 version differed in about 5%. Add a test with sizes that used to get the extra padding.
There was a problem hiding this comment.
Code Review
This pull request updates tf.image.resize_with_pad to compute the resized size and padding using exact integer arithmetic (with int64) instead of float32. This prevents rounding issues where the scaled size could land slightly below a whole number, which previously caused the image to be scaled one pixel short and padded with zeros or placed off-center. Unit tests have been added to verify the correct padding behavior under these rounding conditions. I have no feedback to provide as the implementation is correct and well-tested.
|
Hi @bodapatisaikrishna, Can you please resolve the conflicts? Thank you! |
dmiltr3
left a comment
There was a problem hiding this comment.
Thanks for fixing the float32 rounding inaccuracy in tf.image.resize_with_pad! Using int64 floor division cleanly resolves both the dropped row or column and the off-center padding bugs. Please address these three items:
-
Cover horizontal padding (
p_width > 0) and off-center padding rounding in_assertNoExtraPaddingFromRounding(tensorflow/python/ops/image_ops_test.py:3986-4006):
All three test tuples currently haveheight <= width, sopad_leftandpad_rightare always0. That leaves the positive horizontal-padding path (resized_width < target_widthandp_width > 0intensorflow/python/ops/image_ops_impl.py:1873-1885) untested. Also, the oldfloat32code produced the samep_heightandp_widthon those three tuples, so off-center padding is not tested. Please add a portrait tuple (height > width) and tuples wherefloat32shiftedp_heightandp_widthoff center, and update the docstring:def _assertNoExtraPaddingFromRounding(test, resize_image_with_pad): """Checks resized size and centering when float32 rounding used to be off. For these sizes float32 used to land slightly below a whole number for the scaled size or padding offset, either dropping an image row/column and replacing it with zeros (e.g. 512x512 -> 224x224) or shifting the image one pixel off center (e.g. 39x65 -> 100x100 or 78x65 -> 300x300). Args: test: The test case. resize_image_with_pad: Called as `resize_image_with_pad(image, target_height, target_width, use_tensor_inputs)`. """ # (height, width, target_height, target_width, pad_top, pad_bottom, # pad_left, pad_right) for (height, width, target_height, target_width, pad_top, pad_bottom, pad_left, pad_right) in [ (512, 512, 224, 224, 0, 0, 0, 0), (480, 640, 300, 300, 37, 38, 0, 0), (640, 480, 300, 300, 0, 0, 37, 38), (720, 1280, 600, 600, 131, 132, 0, 0), (39, 65, 100, 100, 20, 20, 0, 0), (78, 65, 300, 300, 0, 0, 25, 25), ]:
-
Reuse the two
int64cross-products and zero constant in_resize_image_with_pad_common(tensorflow/python/ops/image_ops_impl.py:1871-1887):
i_height * i_target_widthandi_width * i_target_heightare each evaluated three times, emitting sixMulops instead of two. Also,math_ops.cast(0, dtypes.int64)is called twice even thoughconstant_opis already imported in this file. Please bind the two products and theint64zero constant once and reuse them:scaled_height = i_height * i_target_width scaled_width = i_width * i_target_height resized_height = math_ops.minimum( i_target_height, scaled_height // i_width) resized_width = math_ops.minimum( i_target_width, scaled_width // i_height) # floor((target - scaled size) / 2), where the scaled size need not be a # whole number. zero = constant_op.constant(0, dtype=dtypes.int64) p_height = math_ops.maximum( zero, (scaled_width - scaled_height) // (2 * i_width)) p_width = math_ops.maximum( zero, (scaled_height - scaled_width) // (2 * i_height)) p_height = math_ops.cast(p_height, dtype=dtypes.int32) p_width = math_ops.cast(p_width, dtype=dtypes.int32)
-
Rebase onto
masterand resolve merge conflicts:
This branch currently has a merge conflict withmaster, which prevents the automated test suite from running. Please rebase your branch onto the latestmasterand resolve the conflict.
…-rounding # Conflicts: # RELEASE.md
Bind the two int64 cross-products and the zero constant once, which emits two Mul ops instead of six. Extend the test with a portrait size, so the horizontal padding path is covered, and with sizes where float32 shifted the image one pixel off center (39x65 to 100x100 and 78x65 to 300x300).
|
Thanks. Updated in c1b8a6b:
|
dmiltr3
left a comment
There was a problem hiding this comment.
All items from the previous review round are addressed. Precomputing the two int64 cross-products and the zero constant in tensorflow/python/ops/image_ops_impl.py keeps the graph compact, and the added portrait and off-center padding test cases in tensorflow/python/ops/image_ops_test.py cover the rounding edge cases cleanly. The RELEASE.md conflict is resolved and all automated checks pass. LGTM!
Fixes #129783
Problem
tf.image.resize_with_padcomputes the scale factor and the resized size in float32, then floors it. When the scaled size is a whole number, float32 often lands just below it, so the image is resized one pixel short of the target and padded with a row or column of zeros. For example, 512x512 -> 224x224 becomes a 223x223 image with a black bottom row and right column, even though the aspect ratio already matches. The padding comes from the same float, so it can also be one pixel off and shift the image. Over 200,000 random size combinations, about 5% are affected, including common ones such as 480x640 -> 300x300 and 720x1280 -> 600x600.Change
_resize_image_with_pad_commonnow evaluates the same formulas in int64 arithmetic:min(target, size * other_target // other_size), which equalsfloor(size / ratio)withratio = max(width / target_width, height / target_height);max(0, (target * other_size - size * other_target) // (2 * other_size)), which equalsfloor((target - size / ratio) / 2).On 200,000 random combinations of sizes from 1 to 2000, these match exact rational arithmetic everywhere. The float32 version differed in 10,099 cases. Wherever float32 was already exact, the results are unchanged. int64 is used so the products cannot overflow for any int32 size. The now-unused
max_helper is removed.Add
testNoExtraPaddingFromRoundingto bothResizeImageWithPadV1TestandResizeImageWithPadV2Test, using sizes that used to get the extra padding.Testing
I don't have a Bazel build. I ran the changed tests with Python against the tf-nightly 2.23.0.dev20261028 macOS arm64 wheel, with this PR's
image_ops_impl.pyandimage_ops_test.pycopied in:Full
image_ops_test.py, with and without this change: no new failures. In both runs, 90 tests error because the wheel doesn't ship the image test-data files, andFormatTest.testErrorfails; neither touches this code.ResizeImageWithPadV1TestandResizeImageWithPadV2Test, includingtestShapeInferencein graph mode: pass. With the oldimage_ops_impl.py, the new test fails in both classes.resize_with_padinsidetf.functionwith unknown height, width and target sizes, underjit_compile=True, withuint8input, and throughtf.compat.v1.image.resize_image_with_pad: correct output.pylint --rcfile=tensorflow/tools/ci_build/pylintrc: no new messages.I did not test on GPU. The change only affects the size arithmetic in Python, so the output now differs only where float32 used to round wrongly. I added a
RELEASE.mdentry because those outputs change.