Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BC-breaking] Fix for integer fill value in constant padding #2284

Merged
merged 3 commits into from
Jun 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion test/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,13 +299,22 @@ def test_pad(self):
width = random.randint(10, 32) * 2
img = torch.ones(3, height, width)
padding = random.randint(1, 20)
fill = random.randint(1, 50)
result = transforms.Compose([
transforms.ToPILImage(),
transforms.Pad(padding),
transforms.Pad(padding, fill=fill),
transforms.ToTensor(),
])(img)
self.assertEqual(result.size(1), height + 2 * padding)
self.assertEqual(result.size(2), width + 2 * padding)
# check that all elements in the padded region correspond
# to the pad value
fill_v = fill / 255
eps = 1e-5
self.assertTrue((result[:, :padding, :] - fill_v).abs().max() < eps)
self.assertTrue((result[:, :, :padding] - fill_v).abs().max() < eps)
self.assertRaises(ValueError, transforms.Pad(padding, fill=(1, 2)),
transforms.ToPILImage()(img))

def test_pad_with_tuple_of_pad_values(self):
height = random.randint(10, 32) * 2
Expand Down
6 changes: 6 additions & 0 deletions torchvision/transforms/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,12 @@ def pad(img, padding, fill=0, padding_mode='constant'):
'Padding mode should be either constant, edge, reflect or symmetric'

if padding_mode == 'constant':
if isinstance(fill, numbers.Number):
fill = (fill,) * len(img.getbands())
fmassa marked this conversation as resolved.
Show resolved Hide resolved
if len(fill) != len(img.getbands()):
raise ValueError('fill should have the same number of elements '
'as the number of channels in the image '
'({}), got {} instead'.format(len(img.getbands()), len(fill)))
if img.mode == 'P':
palette = img.getpalette()
image = ImageOps.expand(img, border=padding, fill=fill)
Expand Down