How to get No. of images in every class by datasets.ImageFolder?

Assume that I have a dataset containing 5 classes of image files. And I use “datasets.ImageFolder” as data loader. I know that I can get the total No. of images and No. of classes as follows:

train_folders = datasets.ImageFolder(train_path, train_transforms)
len(train_folders)  
len(train_folders.classes)

Is there any way that I can get the No. of image files in every Class?

Why do I need that?
I want to use Class weight (= 1/ No. of images).
But, I don’t want to enter No. of images or Class weight manually (hard coding).


I have another question in this regard.
When I run “train_folders[0]”, I get a tuple. Could you explain what is included in the tuple?

I noticed that when I run “train_folders[0][0]”, I get an image of dataset. But, I couldn’t understand the data structure of the mentioned tuple.

Thank you for your time.

You could access the train_folder.targets attribute and use torch.unique(train_folder.targets, return_counts=True) on it to get the number of samples for each target.

5 Likes