147_Spectrogram_labels / DatasetGenerator.py
Will-uob's picture
ExampleLoadingOfDataset
6cb7ca9
raw
history blame
1.64 kB
### Example loading of the dataset
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import ToTensor
import matplotlib.pyplot as plt
import zipfile
import os
import pandas as pd
from torchvision.io import read_image
class CustomImageDataset(Dataset):
def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):
self.img_labels = pd.read_csv(annotations_file)
self.img_dir = img_dir
self.transform = transform
self.target_transform = target_transform
def __len__(self):
return len(self.img_labels)
def __getitem__(self, idx):
img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, -1])
image = read_image(img_path)
label = self.img_labels.iloc[idx, 2]
if self.transform:
image = self.transform(image)
if self.target_transform:
label = self.target_transform(label)
return image, label
with zipfile.ZipFile("150_Dataset(1).zip", 'r') as zip_ref:
zip_ref.extractall(".")
train_dataset = CustomImageDataset(annotations_file="./images/train/train.csv",
img_dir="./images/train")
train_dataloader = DataLoader(train_dataset, batch_size=12, shuffle=True)
train_features, train_labels = next(iter(train_dataloader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {len(train_labels)}")
img = train_features[0].squeeze()
label = train_labels[0]
plt.imshow(img, cmap="gray")
plt.show()
print(f"Label: {label}")