Dataset/Dataloader to Load Batches per Class

My dataset is in the format

root/
    1/
        1.png
        2.png
        3.png
        ...
    2/
        1.png
        2.png
        3.png
        ...
    ...

I need to be able to load batches containing images only from a specific class, for each class.
Eg. (1st batch are 8 images from root/1, 2nd batch are 8 images from root/2, so on)

Is there any way to do so without having multiple datasets, each for a particular class?

Any help is appreciated.

If I understand you correctly, the ImageFolder class does just that:

https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder

But is it possible to specify which class to sample from?

Not with the ImageFolder object. But you could perhaps create an ImageFolder object for each class to be able to sample independently from each class.