How to read just one pic?

I finished my training about a classify network with the help of DataLoader.That’s awesome.

When i use just one pic to test my model, i found that the image read with the help of opencv in the format of array is different from that get from DataLoader.
Is that really different from the result of DataLoader if i read with cv2.imread or did i make some mistake?

If i want to read one pic with the same result as that getting by DataLoader,what can i do ?

It depends how you’ve read the images in your Dataset. The DataLoader just calls Dataset's __getitem__ method.
Did you use torchvision.datasets.ImageFolder?

If so, the images were probably loaded with PIL, if you didn’t install accimage.
You can find the line of code here.

However, you need to provide the batch dimension at dim0, so your code would look like this:

from PIL import Image
import torchvision.transforms.functional as TF

image = Image.open('YOUR_PATH')
x = TF.to_tensor(image)
x.unsqueeze_(0)
print(x.shape)

output = model(X)
8 Likes

Thanks a lot!
I found another question:

when all my pics (n-class)are stored like this:
train/ant/***.jpg .jpg
train/snake/
.jpg .jpg
train/bear/
.jpg ***.jpg

when i use DataLoader,the label is 0n-1,how do pytorch decide that which class is class 0,which is class 1 etc. According to the alphabet order?

Yes, the folders are found using

classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()

The .sort() call sorts the folders in alphabetic order.
You can find the code here.

2 Likes

Thank U!
Wish U a good day!

In newer versions ImageFolder (alias DatasetFolder now) doesn’t read any more images, since logic is given by user-defined callable, right?

ImageFolder is not an alias for DatasetFolder, but uses is as its base class (which was this case for a while now). You are correct: if you need more flexibility in e.g. the image loading etc. you can derive your custom dataset from DatasetFolder.

1 Like