-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomTensorDataset.py
30 lines (24 loc) · 942 Bytes
/
CustomTensorDataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import os
from PIL import Image
from torch.utils.data import Dataset
from natsort import natsorted
from torchvision import datasets, transforms
# Define your own class LoadFromFolder
class LoadFromFolder(Dataset):
def __init__(self, main_dir, transform):
# Set the loading directory
self.main_dir = main_dir
self.transform = transform
# List all images in folder and count them
all_imgs = os.listdir(main_dir)
self.total_imgs = natsorted(all_imgs)
def __len__(self):
# Return the previously computed number of images
return len(self.total_imgs)
def __getitem__(self, idx):
img_loc = os.path.join(self.main_dir, self.total_imgs[idx])
# Use PIL for image loading
image = Image.open(img_loc).convert("RGB")
# Apply the transformations
tensor_image = self.transform(image)
return tensor_image