Skip to content

Addresses issue #145 as per @fmessa's suggestion. #527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 6, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions torchvision/datasets/folder.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,10 @@ def is_image_file(filename):
return has_file_allowed_extension(filename, IMG_EXTENSIONS)


def find_classes(dir):
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx


def make_dataset(dir, class_to_idx, extensions):
images = []
dir = os.path.expanduser(dir)
for target in sorted(os.listdir(dir)):
for target in sorted(class_to_idx.keys()):
d = os.path.join(dir, target)
if not os.path.isdir(d):
continue
Expand Down Expand Up @@ -86,7 +79,7 @@ class DatasetFolder(data.Dataset):
"""

def __init__(self, root, loader, extensions, transform=None, target_transform=None):
classes, class_to_idx = find_classes(root)
classes, class_to_idx = self._find_classes(root)
samples = make_dataset(root, class_to_idx, extensions)
if len(samples) == 0:
raise(RuntimeError("Found 0 files in subfolders of: " + root + "\n"
Expand All @@ -104,6 +97,24 @@ def __init__(self, root, loader, extensions, transform=None, target_transform=No
self.transform = transform
self.target_transform = target_transform

def _find_classes(self, dir):
"""
Finds the class folders in a dataset.

Args:
dir (string): Root directory path.

Returns:
tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.

Ensures:
No class is a subdirectory of another.
"""
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx

def __getitem__(self, index):
"""
Args:
Expand Down