'How to resize image tensors

The following is my code where I'm converting every image to PIL and then turning them into Pytorch tensors:

transform = transforms.Compose([transforms.PILToTensor()])

# choose the training and test datasets
train_data = os.listdir('data/training/')
testing_data = os.listdir('data/testing/')
train_tensors = []
test_tensors = []

for train_image in train_data:
    img = Image.open('data/training/' + train_image)
    train_tensors.append(transform(img))

for test_image in testing_data:
    img = Image.open('data/testing/' + test_image)
    test_tensors.append(transform(img))

# Print out some stats about the training and test data
print('Train data, number of images: ', len(train_data))
print('Test data, number of images: ', len(testing_data))

batch_size = 20

train_loader = DataLoader(train_tensors, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_tensors, batch_size=batch_size, shuffle=True)

# specify the image classes
classes = ['checked', 'unchecked', 'other']

# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy()

However, I am getting this error:

RuntimeError: stack expects each tensor to be equal size, but got [4, 66, 268] at entry 0 and [4, 88, 160] at entry 1

This is because my images are not resized prior to PIL -> Tensor. What is the correct way of resizing data images?



Solution 1:[1]

Try to utilize ImageFolder from torchvision, and assuming that images have diff size, you can use CenterCrop or RandomResizedCrop depending on your task. Check the Full list.

Here is an example:

train_dir = "data/training/"

train_dataset = datasets.ImageFolder(
    train_dir,
    transforms.Compose([
        transforms.RandomResizedCrop(img_size),  # image size int or tuple
        # Add more transforms here
        transforms.ToTensor(),  # convert to tensor at the end
]))

train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 trsvchn