Skip to content

Commit a188bcd

Browse files
vfdev-5datumbox
andauthored
Fixed issue with F.crop when cropping outside the input image (#6615)
Co-authored-by: Vasilis Vryniotis <[email protected]>
1 parent 2a5fbcd commit a188bcd

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

test/test_functional_tensor.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,6 +1104,8 @@ def test_hflip(device):
11041104
(2, 12, 3, 4), # crop inside top-right corner
11051105
(8, 3, 5, 6), # crop inside bottom-left corner
11061106
(8, 11, 4, 3), # crop inside bottom-right corner
1107+
(50, 50, 10, 10), # crop outside the image
1108+
(-50, -50, 10, 10), # crop outside the image
11071109
],
11081110
)
11091111
def test_crop(device, top, left, height, width):

torchvision/transforms/functional_tensor.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,12 @@ def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
137137
bottom = top + height
138138

139139
if left < 0 or top < 0 or right > w or bottom > h:
140-
padding_ltrb = [max(-left, 0), max(-top, 0), max(right - w, 0), max(bottom - h, 0)]
140+
padding_ltrb = [
141+
max(-left + min(0, right), 0),
142+
max(-top + min(0, bottom), 0),
143+
max(right - max(w, left), 0),
144+
max(bottom - max(h, top), 0),
145+
]
141146
return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0)
142147
return img[..., top:bottom, left:right]
143148

0 commit comments

Comments
 (0)