Skip to content

Commit

Permalink
Add support in transforms.ToTensor for PIL Images mod '1' (#471)
Browse files Browse the repository at this point in the history
* Add case in test_to_tensor for PIL Images mode '1'

* Add support in ToTensor for PIL Images mode '1'

* Fix pep8 issues
  • Loading branch information
arturml authored and fmassa committed Apr 16, 2018
1 parent 7bda0e8 commit f6ab107
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 6 additions & 0 deletions test/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,12 @@ def test_to_tensor(self):
expected_output = ndarray.transpose((2, 0, 1))
assert np.allclose(output.numpy(), expected_output)

# separate test for mode '1' PIL images
input_data = torch.ByteTensor(1, height, width).bernoulli_()
img = transforms.ToPILImage()(input_data.mul(255)).convert('1')
output = trans(img)
assert np.allclose(input_data.numpy(), output.numpy())

@unittest.skipIf(accimage is None, 'accimage not available')
def test_accimage_to_tensor(self):
trans = transforms.ToTensor()
Expand Down
4 changes: 3 additions & 1 deletion torchvision/transforms/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ def to_tensor(pic):
img = torch.from_numpy(np.array(pic, np.int16, copy=False))
elif pic.mode == 'F':
img = torch.from_numpy(np.array(pic, np.float32, copy=False))
elif pic.mode == '1':
img = 255 * torch.from_numpy(np.array(pic, np.uint8, copy=False))
else:
img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes()))
# PIL image mode: 1, L, P, I, F, RGB, YCbCr, RGBA, CMYK
# PIL image mode: L, P, I, F, RGB, YCbCr, RGBA, CMYK
if pic.mode == 'YCbCr':
nchannel = 3
elif pic.mode == 'I;16':
Expand Down

0 comments on commit f6ab107

Please sign in to comment.