Skip to content

Commit 217e26f

Browse files
jamt9000vfdev-5
andauthored
Negative padding for functional_tensor symmetric (#2749)
* Negative padding for functional_tensor symmetric Along with #2744 this will make negative padding uniform between PIL and Tensor #2381 * Enable tests for negative symmetric pad with tensor Co-authored-by: vfdev <[email protected]>
1 parent 6b41eb0 commit 217e26f

File tree

3 files changed

+8
-8
lines changed

3 files changed

+8
-8
lines changed

test/test_functional_tensor.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -285,9 +285,6 @@ def test_pad(self):
285285

286286
self._test_fn_on_batch(batch_tensors, F.pad, padding=script_pad, **kwargs)
287287

288-
with self.assertRaises(ValueError, msg="Padding can not be negative for symmetric padding_mode"):
289-
F_t.pad(tensor, (-2, -3), padding_mode="symmetric")
290-
291288
def _test_adjust_fn(self, fn, fn_pil, fn_t, configs, tol=2.0 + 1e-10, agg_method="max"):
292289
script_fn = torch.jit.script(fn)
293290
torch.manual_seed(15)

test/test_transforms_tensor.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,9 +123,7 @@ def test_color_jitter(self):
123123
def test_pad(self):
124124
for m in ["constant", "edge", "reflect", "symmetric"]:
125125
fill = 127 if m == "constant" else 0
126-
# Negative pad currently unsupported for Tensor and symmetric
127-
multipliers = [1] if m == "symmetric" else [1, -1]
128-
for mul in multipliers:
126+
for mul in [1, -1]:
129127
# Test functional.pad (PIL and Tensor) with padding as single int
130128
self._test_functional_op(
131129
"pad", fn_kwargs={"padding": mul * 2, "fill": fill, "padding_mode": m}

torchvision/transforms/functional_tensor.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,13 @@ def _hsv2rgb(img):
621621

622622
def _pad_symmetric(img: Tensor, padding: List[int]) -> Tensor:
623623
# padding is left, right, top, bottom
624+
625+
# crop if needed
626+
if padding[0] < 0 or padding[1] < 0 or padding[2] < 0 or padding[3] < 0:
627+
crop_left, crop_right, crop_top, crop_bottom = [-min(x, 0) for x in padding]
628+
img = img[..., crop_top:img.shape[-2] - crop_bottom, crop_left:img.shape[-1] - crop_right]
629+
padding = [max(x, 0) for x in padding]
630+
624631
in_sizes = img.size()
625632

626633
x_indices = [i for i in range(in_sizes[-1])] # [0, 1, 2, 3, ...]
@@ -723,8 +730,6 @@ def pad(img: Tensor, padding: List[int], fill: int = 0, padding_mode: str = "con
723730
padding_mode = "replicate"
724731
elif padding_mode == "symmetric":
725732
# route to another implementation
726-
if p[0] < 0 or p[1] < 0 or p[2] < 0 or p[3] < 0: # no any support for torch script
727-
raise ValueError("Padding can not be negative for symmetric padding_mode")
728733
return _pad_symmetric(img, p)
729734

730735
need_squeeze = False

0 commit comments

Comments
 (0)