diff --git a/test/test_functional_tensor.py b/test/test_functional_tensor.py index 1914bc571fb..781aefe786f 100644 --- a/test/test_functional_tensor.py +++ b/test/test_functional_tensor.py @@ -1104,6 +1104,8 @@ def test_hflip(device): (2, 12, 3, 4), # crop inside top-right corner (8, 3, 5, 6), # crop inside bottom-left corner (8, 11, 4, 3), # crop inside bottom-right corner + (50, 50, 10, 10), # crop outside the image + (-50, -50, 10, 10), # crop outside the image ], ) def test_crop(device, top, left, height, width): diff --git a/torchvision/transforms/functional_tensor.py b/torchvision/transforms/functional_tensor.py index e268acbb6e0..4613a95e926 100644 --- a/torchvision/transforms/functional_tensor.py +++ b/torchvision/transforms/functional_tensor.py @@ -137,7 +137,12 @@ def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor: bottom = top + height if left < 0 or top < 0 or right > w or bottom > h: - padding_ltrb = [max(-left, 0), max(-top, 0), max(right - w, 0), max(bottom - h, 0)] + padding_ltrb = [ + max(-left + min(0, right), 0), + max(-top + min(0, bottom), 0), + max(right - max(w, left), 0), + max(bottom - max(h, top), 0), + ] return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0) return img[..., top:bottom, left:right]