ImageFolder#
- class deeptrack.sources.folder.ImageFolder(root: str)#
Bases:
SourceData source for images organized in a directory structure.
ImageFolder scans a directory tree where images are stored under subdirectories that represent their categorical labels. It automatically assigns integer labels, stores paths and names, and supports operations such as splitting by folder and category lookup.
It behaves like a standard Source, returning SourceItem objects that include image file paths, label indices, and label names. This allows seamless integration with feature pipelines in DeepTrack2.
Labeling is always based on the first path component under the provided root. If root contains split folders (e.g., train/, test/), call .split() first or pass root/train as the root for class labeling. Note that after splitting, labels are re-inferred relative to the new root, so flat folders will use filenames as label_name.
Notes#
split() returns new ImageFolder instances rooted at root/<split>. Each returned dataset re-infers labels relative to its new root using the same rule as ImageFolder: the first path component under that root. If root/<split> contains images directly (no subfolders), filenames become the label_name.
Parameters#
- root: str
Path to the root directory that contains subfolders of images. The first-level subfolder names are interpreted as categories.
Attributes#
- _category_to_int: dict[str, int]
Mapping from category name to numeric label.
- _int_to_category: dict[int, str]
Mapping from numeric label to category name.
- _paths: list[str]
Internal list of all file paths.
- _length: int
Total number of images discovered.
- _root: str
Root directory provided by the user.
Methods#
- __len__() -> int
Return the number of image files found.
- classes -> list[str]
Return a list of unique class names found in the directory.
- get_category_name(path, directory_level) -> str
Return the category name for a given image path.
- label_to_name(label) -> str
Convert an integer label back to its string category name.
- name_to_label(name) -> int
Convert a string category name to its integer label.
- split(*splits) -> tuple[ImageFolder, …]
Return one or more subsets of the data based on top-level folder names.
Examples#
Create a dummy dataset structure with train/test subfolders
>>> import os >>> import shutil
Temporary root directory:
>>> root = "tmp_data"
Remove existing directory if needed:
>>> if os.path.exists(root): ... shutil.rmtree(root)
Define splits and classes: >>> splits = [“train”, “test”] >>> classes = [“cat”, “dog”, “bird”]
Create directories and dummy files:
>>> for split in splits: ... for cls in classes: ... folder_path = os.path.join(root, split, cls) ... os.makedirs(folder_path) ... for i in range(2): ... file_path = os.path.join(folder_path, f"image_{i}.jpg") ... with open(file_path, "w") as f: ... f.write("dummy")
Load a split of the dataset, specifically, the training set:
>>> from deeptrack.sources.folder import ImageFolder >>> >>> train_data = ImageFolder(os.path.join(root, "train"))
>>> len(train_data) 6 >>> train_data.classes ['bird', 'dog', 'cat']
>>> train_data.path() 'tmp_data/train/bird/image_0.jpg'
Access a source item
>>> item = train_data[0]
>>> item["path"] 'tmp_data/train/bird/image_0.jpg'
>>> item["label"] 0
>>> item["label_name"] 'bird'
Convert between label names and indices
>>> train_data.name_to_label("cat") 2
>>> train_data.label_to_name(0) 'bird'
Split the dataset across top-level folders
>>> all_data = ImageFolder(root) >>> train, test = all_data.split("train", "test")
>>> print(f"Train size: {len(train)}") Train size: 6
>>> print(f"Test size: {len(test)}") Test size: 6
Print paths in each split
Train files:
>>> for item in train: ... print(item["path"]) tmp_data/train/bird/image_0.jpg tmp_data/train/bird/image_1.jpg tmp_data/train/cat/image_0.jpg tmp_data/train/cat/image_1.jpg tmp_data/train/dog/image_0.jpg tmp_data/train/dog/image_1.jpg
Test files:
>>> for item in test: ... print(item["path"]) tmp_data/test/bird/image_0.jpg tmp_data/test/bird/image_1.jpg tmp_data/test/cat/image_0.jpg tmp_data/test/cat/image_1.jpg tmp_data/test/dog/image_0.jpg tmp_data/test/dog/image_1.jpg
Attributes Summary
List of category names in the dataset.
Methods Summary
get_category_name(path, directory_level)Extract the category name from file path at given directory level.
label_to_name(label)Convert an integer label to its corresponding category name.
name_to_label(name)Convert a category name to its corresponding integer label.
split(*splits)Split the dataset into subsets by folder name.
Attributes Documentation
- classes#
List of category names in the dataset.
Returns#
- list[str]
A list of unique category names corresponding to the top-level directories found under the root folder.
Methods Documentation
- get_category_name(path: str, directory_level: int) str#
Extract the category name from file path at given directory level.
This method determines the category name (i.e., the name of the directory at the specified directory_level relative to the root) associated with the given file path.
Parameters#
- path: str
The absolute path to the image file.
- directory_level: int
The index of the directory component to extract, relative to the root.
Returns#
- str
The name of the folder at the given level in the path.
- label_to_name(label: int) str#
Convert an integer label to its corresponding category name.
Given a numeric label (e.g., 0, 1, 2), return the associated category name (e.g., “cat”, “dog”) that was assigned during initialization.
Parameters#
- label: int
The integer label representing a category.
Returns#
- str
The name of the category corresponding to the label.
- name_to_label(name: str) int#
Convert a category name to its corresponding integer label.
Given a category name (e.g., “cat”, “dog”), return the integer label (e.g., 0, 1) assigned to it during initialization.
Parameters#
- name: str
The name of the category.
Returns#
- int
The integer label corresponding to the category name.
- split(*splits: str) tuple[ImageFolder, ...]#
Split the dataset into subsets by folder name.
This method splits the dataset into subsets based on the first folder name in the path of each image. It is useful when datasets are stored in separate directories (e.g., train, test, val), and you want to retrieve subsets accordingly.
If no arguments are given, it returns one ImageFolder per top-level directory found under the root. If specific names are provided, only those subsets are returned.
Parameters#
- *splits: str
Names of the subfolders (relative to the root) to split into.
Returns#
- tuple[ImageFolder, …]
A tuple of ImageFolder instances, one per requested split.
Raises#
- ValueError
If an unknown split name is provided or no categories are found.