Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions test/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
except ImportError:
accimage = None

try:
from scipy import stats
except ImportError:
stats = None


GRACE_HOPPER = 'assets/grace_hopper_517x606.jpg'

Expand Down Expand Up @@ -327,6 +332,34 @@ def test_ndarray_gray_int32_to_pil_image(self):
assert img.mode == 'I'
assert np.allclose(img, img_data[:, :, 0])

@unittest.skipIf(stats is None, 'scipy.stats not available')
def test_random_vertical_flip(self):
img = transforms.ToPILImage()(torch.rand(3, 10, 10))
vimg = img.transpose(Image.FLIP_TOP_BOTTOM)

num_vertical = 0
for _ in range(100):
out = transforms.RandomVerticalFlip()(img)
if out == vimg:
num_vertical += 1

p_value = stats.binom_test(num_vertical, 100, p=0.5)
assert p_value > 0.05

@unittest.skipIf(stats is None, 'scipy.stats not available')
def test_random_horizontal_flip(self):
img = transforms.ToPILImage()(torch.rand(3, 10, 10))
himg = img.transpose(Image.FLIP_LEFT_RIGHT)

num_horizontal = 0
for _ in range(100):
out = transforms.RandomHorizontalFlip()(img)
if out == himg:
num_horizontal += 1

p_value = stats.binom_test(num_horizontal, 100, p=0.5)
assert p_value > 0.05


if __name__ == '__main__':
unittest.main()
16 changes: 16 additions & 0 deletions torchvision/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,22 @@ def __call__(self, img):
return img


class RandomVerticalFlip(object):
"""Vertically flip the given PIL.Image randomly with a probability of 0.5"""

def __call__(self, img):
"""
Args:
img (PIL.Image): Image to be flipped.

Returns:
PIL.Image: Randomly flipped image.
"""
if random.random() < 0.5:
return img.transpose(Image.FLIP_TOP_BOTTOM)
return img


class RandomSizedCrop(object):
"""Crop the given PIL.Image to random size and aspect ratio.

Expand Down