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.