Dataloader with single image

Hi all,

I am new to Pytorch and not sure if it is possible to create a DataLoader that can read and repeat the same image over and over. I have an example implementation in Tensorflow:

N = 1000
img = tf.keras.preprocessing.image.load_img(path)
tds = tf.data.Dataset.from_tensor_slices(img).repeat(N)

Thanks in advance.

You could try something as below:

import torch, torch.utils.data as data
x = torch.randn(3,25,25)
N = 10
ds = data.TensorDataset(x.unsqueeze(0).repeat(N,1,1,1))
for item in ds:
    img = item[0]
    print(img.shape)

You can also create a Dataset class which returns the same image, len of 1000 for 1000 instances and returns the same image in getitem

from torch.utils.data import Dataset
class data(Dataset):
    def __init__(self, image_path, transform=None):
        self.image_path = image_path
        self.transform = transform

    def __len__(self):
        return 1000

    def __getitem__(self, x):
        # open image here as PIL / numpy
        image = #load image here
        label = # if label
        if self.transform is not None:
            image = self.transform(image)

        return image, label

Then pass this dataset to the Dataloader

1 Like