Trying to use transforms on an ndarray fails

Any help will be much appreciated. The code in transforms.py says that the transformation should/would apply to PIL images as well as ndarrays. Given the transforms:

data_transforms = {
    'train': transforms.Compose([
        transforms.Scale(256),
        transforms.Pad(4,0),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
    'val': transforms.Compose([
        transforms.Scale(256),
        transforms.Pad(4,0),
        transforms.ToTensor(),
        transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
    ]),
}

I wish to apply the transform on ndarrays that I obtained from some other code. Let’s say it is x_data, whose shape is (1000,120,160,3) where the dimensions are (total rows, width, height, channels)

doing the following fails (All I’m trying to do is apply a transformation) :

foo = data_transforms['train']
bar = foo(x_data[0])

with the following message:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-93-a703e3b9c76d> in <module>()
----> 1 foo(x_data[1])

~/anaconda3/envs/pytorch/lib/python3.5/site-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py in __call__(self, img)
     32     def __call__(self, img):
     33         for t in self.transforms:
---> 34             img = t(img)
     35         return img
     36 

~/anaconda3/envs/pytorch/lib/python3.5/site-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py in __call__(self, img)
    185         """
    186         if isinstance(self.size, int):
--> 187             w, h = img.size
    188             if (w <= h and w == self.size) or (h <= w and h == self.size):
    189                 return img

TypeError: 'int' object is not iterable
1 Like

Hello,

It’s transforms.Scale() (renamed to transforms.Resize()in the current master) which is failing to operate on ndarray. The current master first checks if the input is a PIL image or not before proceeding.

Haven’t tried it yet, but I’m thinking “Image.fromarray(x_data[0]” as listed here: https://stackoverflow.com/questions/30345937/how-to-read-image-from-numpy-array-into-pil-image

However, I did want to ask if the error-trace above could be attributed the reason you stated. It does seem like the execution passes beyond the check for PIL_Image, and the error occurs when this line is hit.

Thanks anyways…

I think the latest version in GitHub differs in terms of those codepaths. Scale is now obsoleted by Resize . There’s also ToPILImage() in transforms that you can use to convert from a Torch tensor or ndarray to PIL Image.