How to convert an list of image into Pytorch Tensor

Viewed 6827

I have a list called wordImages. It contains images in np.array format with different width & height.

How Do I convert this into a tensor and use this instead of my_dataset in the below code?

Currently i am using this. But I need to save/read images

demo_data = RawDataset(root="output_craft/", opt=opt) 

demo_loader = torch.utils.data.DataLoader(
                demo_data , batch_size=opt.batch_size,
                shuffle=False,
                num_workers=int(opt.workers),
                collate_fn=AlignCollate_demo, pin_memory=True)
1 Answers

You can use transforms from the torchvision library to do so. You can pass whatever transformation(s) you declare as an argument into whatever class you use to create my_dataset, like so:

from torchvision import transforms as transforms

class MyDataset(data.Dataset):

    def __init__(self, transform=transforms.ToTensor()):
        self.transform = transform
        ...
    def __getitem__(self, idx):
        ...
        img_tensor = self.transform(img)
        return (img_tensor, label)
Related