2

There are rectangular images in train & validation folders, and the images are accessed via Pytorch through DataLoader module. Without performing,

transforms.CenterCrop(size) or transforms.RandomCrop(size)

I need to preserve their original shape and size, so that while training/testing I can input square-shaped images, via some custom cropping technique. This CustomCrop function may take as inputs certain parameters, different for different images.

When I tried this custom-cropping approach only for testing, I had to exclude the cropping line from data_transforms for TEST.

data_transforms = {
    TRAIN: transforms.Compose([
        transforms.RandomCrop(size),
        transforms.ToTensor(),
    ]),
    TEST: transforms.Compose([
        #CROPPING LINE EXCLUDED FROM HERE
        transforms.ToTensor(),
    ])
}
image_datasets = {
    x: ImageFolder(
        os.path.join(path, mapping[x]), 
        transform=data_transforms[x]
    )
    for x in [TRAIN, TEST]
}
dataloaders = {
       x: DataLoader(
       image_datasets[x], batch_size=batch_size
       )
    for x in [TRAIN, TEST]
}    

And my intention is to do something like...

for imgs, lbls, paths in iter(dataloaders[TEST]):
    data = (imgs, lbls)
    inputs, labels = data
    cropped_input = myCustomCrop(inputs, param1, param2) #this crops it to square size, compatible for my model
    [...]  #some code      
    optimizer.zero_grad()            
    outputs = model(cropped_input)

...so that I can crop it during run-time as per my need.

But this gives me an error message (For image size (100,75) in folder):

--> 218     for imgs, lbls, paths in iter(dataloaders[TEST]):
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 100 and 75 in dimension 2 at ...

I am understanding that, DataLoader stacks the images and they need to be equal-sized at runtime. But, how can I then implement my custom-crop function, which may be different for different images (based on input parameter to CustomCrop function). Any suggestions would be highly appreciated. Thanks.

Prithwish Jana
  • 317
  • 2
  • 11
  • 1
    I presume that your custom crop function will output images of similar shapes. If that is the case, one solution be to extend your own `CustomDataset` class from `ImageFolder` were you may apply custom crop. – asymptote Aug 22 '19 at 02:24
  • Otherwise, you can write a custom collate function for Dataloader to return list of size `batch_size` containing image tensors. – asymptote Aug 22 '19 at 02:26
  • But I actually want my CustomCrop function to output images based on some input parameters...parameters may differ for different images... I have edited the question now...the question may have been a little unclear earlier... – Prithwish Jana Aug 22 '19 at 08:57

0 Answers0