I usually use a custom dataset class for this type of problems and in the __init__ method read the name of images and do sorting and other stuff if needed and then in the __getitem__ method, load the image and do the processing and return the image and its label. You can have a lot of freedom and can control everything in the class. You can check this 52 tutorial for more details.