How to convert a list of images into a Pytorch Tensor

Question:

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)
Asked By: rahul sharma

||

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)
Answered By: ccl
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.