Skip to content

RandomHorizontalFlip can handle both PIL Image and numpy ndarray #141

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

Closed
wants to merge 2 commits into from
Closed
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
25 changes: 20 additions & 5 deletions torchvision/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import random
from PIL import Image, ImageOps
import numpy as np
import scipy as sp
from scipy import misc
import numbers
import types

Expand Down Expand Up @@ -127,17 +129,27 @@ def __init__(self, size, interpolation=Image.BILINEAR):
self.interpolation = interpolation

def __call__(self, img):
w, h = img.size
if isinstance(img, np.ndarray):
w, h, c = img.shape
else:
w, h = img.size

if (w <= h and w == self.size) or (h <= w and h == self.size):
return img
if w < h:
ow = self.size
oh = int(self.size * h / w)
return img.resize((ow, oh), self.interpolation)
if isinstance(img, np.ndarray):
return misc.imresize(img, (oh, ow, c))
else:
return img.resize((ow, oh), self.interpolation)
else:
oh = self.size
ow = int(self.size * w / h)
return img.resize((ow, oh), self.interpolation)
if isinstance(img, np.ndarray):
return misc.imresize(img, (oh, ow, c))
else:
return img.resize((ow, oh), self.interpolation)


class CenterCrop(object):
Expand Down Expand Up @@ -212,12 +224,15 @@ def __call__(self, img):


class RandomHorizontalFlip(object):
"""Randomly horizontally flips the given PIL.Image with a probability of 0.5
"""Randomly horizontally flips the given PIL.Image or np.ndarray with a probability of 0.5
"""

def __call__(self, img):
if random.random() < 0.5:
return img.transpose(Image.FLIP_LEFT_RIGHT)
if isinstance(img, np.ndarray):
return np.fliplr(img)
else:
return img.transpose(Image.FLIP_LEFT_RIGHT)
return img


Expand Down