o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
make simple pytorch dataset that loads images from directory and returns them
- User
make simple pytorch dataset that loads images from directory and returns them
- Assistant
make simple pytorch dataset that loads images from directory and returns them
Certainly! Here's a simple PyTorch Dataset class that loads images from a directory and returns them. This class inherits from torch.utils.data.Dataset and overrides the __len__ and __getitem__ methods.
import os
from PIL import Image
from torch.utils.data import Dataset
class ImageDataset(Dataset):
def __init__(self, img_dir, transform=None):
"""
Args:
img_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on an image.
"""
self.img_dir = img_dir
self.image_names = os.listdir(img_dir)
self.transform = transform
def __len__(self):
return len(self.image_names)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
# Get image path
img_name = self.image_names[idx]
img_path = os.path.join(self.img_dir, img_name)
# Load image
image = Image.open(img_path).convert('RGB') # Convert to RGB
# Apply transformations if any
if self.transform:
image = self.transform(image)
return image
Usage Example:
from torchvision import transforms
from torch.utils.data import DataLoader
# Define any transformations you want to apply to the images
transform = transforms.Compose([
transforms.Resize((128, 128)),
transforms.ToTensor(),
])
# Create the dataset
dataset = ImageDataset(img_dir='path/to/your/image_directory', transform=transform)
# Optionally, create a DataLoader to iterate over the dataset
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
# Iterate over the DataLoader
for images in dataloader:
# Your training code here
pass
Explanation:
__init__:
transform parameter for preprocessing.__len__:
__getitem__:
Image.open.Notes:
Image Transformations:
DataLoader:
DataLoader allows you to batch and shuffle the data efficiently.File Types:
self.image_names to include only image files (e.g., files ending with .jpg, .png).Filtering for Image Files (Optional):
If your directory contains non-image files, modify the initialization to filter out non-image files:
from torchvision.datasets.folder import has_file_allowed_extension, IMG_EXTENSIONS
class ImageDataset(Dataset):
def __init__(self, img_dir, transform=None):
self.img_dir = img_dir
# Filter out files that are not images
self.image_names = [
fname for fname in os.listdir(img_dir)
if has_file_allowed_extension(fname, IMG_EXTENSIONS)
]
self.transform = transform
# Rest of the class remains the same...
This ensures only supported image file extensions are included.
This simple dataset class should help you load images from a directory for use in training or inference with PyTorch models.
Not yet included in a published release.