Can transforms.Compose handle a batch of Images?

I have a preprocessing pipeling with transforms.Compose(). However, I’m wondering if this can also handle batches in the same way as nn.Sequential() ?

A minimal example, where the img_batch creation doesn’t work obviously…

import torch
from torchvision import transforms
from PIL import Image

img1 = Image.open('img1')
img2 = Image.open('img2')
img3 = Image.open('img3')

img_batch = torch.Tensor([img1, img2, img3])

preproc = transforms.Compose([
    transforms.ToTensor()
])

preproc(img_batch)
4 Likes

Check this discussion: https://github.com/pytorch/vision/issues/157.

thanks, so the simple answer is no. :neutral_face:

3 years later … haha

1 Like

Yes, it can, if you pass tensors to it:

transform = transforms.Compose([
    transforms.RandomCrop(24),
    transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
])

x = torch.randn(64, 3, 30, 30)
out = transform(x)
print(out.shape)
> torch.Size([64, 3, 24, 24])

CC @JosueCom

7 Likes

Happy to see this development in the latest version of torchvision. Kudos :slight_smile:

1 Like