ExampleLoadingOfDataset
Browse files- DatasetGenerator.py +48 -0
DatasetGenerator.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
### Example loading of the dataset
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch.utils.data import Dataset
|
| 5 |
+
from torchvision import datasets
|
| 6 |
+
from torchvision.transforms import ToTensor
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import zipfile
|
| 9 |
+
import os
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from torchvision.io import read_image
|
| 12 |
+
|
| 13 |
+
class CustomImageDataset(Dataset):
|
| 14 |
+
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
|
| 15 |
+
self.img_labels = pd.read_csv(annotations_file)
|
| 16 |
+
self.img_dir = img_dir
|
| 17 |
+
self.transform = transform
|
| 18 |
+
self.target_transform = target_transform
|
| 19 |
+
|
| 20 |
+
def __len__(self):
|
| 21 |
+
return len(self.img_labels)
|
| 22 |
+
|
| 23 |
+
def __getitem__(self, idx):
|
| 24 |
+
img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, -1])
|
| 25 |
+
image = read_image(img_path)
|
| 26 |
+
label = self.img_labels.iloc[idx, 2]
|
| 27 |
+
if self.transform:
|
| 28 |
+
image = self.transform(image)
|
| 29 |
+
if self.target_transform:
|
| 30 |
+
label = self.target_transform(label)
|
| 31 |
+
return image, label
|
| 32 |
+
|
| 33 |
+
with zipfile.ZipFile("150_Dataset(1).zip", 'r') as zip_ref:
|
| 34 |
+
zip_ref.extractall(".")
|
| 35 |
+
|
| 36 |
+
train_dataset = CustomImageDataset(annotations_file="./images/train/train.csv",
|
| 37 |
+
img_dir="./images/train")
|
| 38 |
+
|
| 39 |
+
train_dataloader = DataLoader(train_dataset, batch_size=12, shuffle=True)
|
| 40 |
+
|
| 41 |
+
train_features, train_labels = next(iter(train_dataloader))
|
| 42 |
+
print(f"Feature batch shape: {train_features.size()}")
|
| 43 |
+
print(f"Labels batch shape: {len(train_labels)}")
|
| 44 |
+
img = train_features[0].squeeze()
|
| 45 |
+
label = train_labels[0]
|
| 46 |
+
plt.imshow(img, cmap="gray")
|
| 47 |
+
plt.show()
|
| 48 |
+
print(f"Label: {label}")
|