|
| 1 | +import os |
| 2 | +import torch |
| 3 | +from torch.utils.data import Dataset |
| 4 | +from PIL import Image |
| 5 | +import torchvision |
| 6 | +import torchaudio |
| 7 | +import numpy as np |
| 8 | +import sys |
| 9 | + |
| 10 | +class GenericLoader(Dataset): |
| 11 | + """A generic dataset loader. |
| 12 | + Suitable for classification, segmentation and regression datasets. |
| 13 | + Supports image, audio, and numpy array files. |
| 14 | +
|
| 15 | + Args: |
| 16 | + path (str): |
| 17 | + path to the dataset |
| 18 | +
|
| 19 | + classification (bool): |
| 20 | + True: classification dataset (single class prediction: class1, class2, ...) |
| 21 | + False: segmentation or regression dataset (multiple components: input, target, ...) |
| 22 | +
|
| 23 | + separator (str or None): |
| 24 | + '/': folders will be used to determine classes or components |
| 25 | + (classes: class1/1.ext, class1/2.ext, class2/1.ext, class2/2.ext, ...) |
| 26 | + (components: inputs/1.ext, inputs/2.ext, targets/1.ext, targets/2.ext, ...) |
| 27 | +
|
| 28 | + '_' or other separator: file name parts will be used to determine classes or components |
| 29 | + (classes: class1_1.ext, class1_2.ext, class2_1.ext, class2_2.ext, ...) |
| 30 | + (components: 1_input.ext, 1_output.ext, 2_input.ext, 2_output.ext, ...) |
| 31 | +
|
| 32 | + '' or None: file names or their content will be used to determine components |
| 33 | + (one sample per folder: 1/input.ext, 1/output.ext, 2/input.ext, 2/output.ext, ...) |
| 34 | + (samples in one folder: 1.ext, 2.ext, ...) |
| 35 | +
|
| 36 | + extensions (str): |
| 37 | + file extension to filters (such as: .jpg, .jpeg, .png, .mp3, .wav, .npy, .npz) |
| 38 | +
|
| 39 | + transforms (list): |
| 40 | + list of transforms to apply to the different components of each sample (use None is some components need no transform) |
| 41 | + (ie: [torchvision.transforms.Compose([transforms.Resize(64)]), torchaudio.transforms.Spectrogram()]) |
| 42 | + """ |
| 43 | + |
| 44 | + def __init__(self, path:str='', classification:bool=True, separator:str='/', extensions:str='.jpg, .jpeg, .png, .mp3, .wav, .npy, .npz', transforms=[]): |
| 45 | + exts = tuple(extensions.replace(' ','').split(',')) |
| 46 | + paths = [] |
| 47 | + self.samples = [] |
| 48 | + self.classes = [] |
| 49 | + self.transforms = transforms |
| 50 | + if not os.path.exists(path): |
| 51 | + print("Path not found.", file=sys.stderr) |
| 52 | + return |
| 53 | + for root, dirs, files in os.walk(path): |
| 54 | + for file in files: |
| 55 | + if file.endswith(exts): |
| 56 | + paths.append(os.path.join(root, file).replace('\\','/')) |
| 57 | + paths=sorted(paths) |
| 58 | + if not paths: |
| 59 | + print("No files found.", file=sys.stderr) |
| 60 | + return |
| 61 | + self.classification=classification |
| 62 | + if classification: |
| 63 | + if separator == '/': |
| 64 | + for path in paths: |
| 65 | + class_name=path.split('/')[-2] |
| 66 | + if class_name not in self.classes: |
| 67 | + self.classes.append(class_name) |
| 68 | + self.samples.append([path, self.classes.index(class_name)]) |
| 69 | + elif separator: |
| 70 | + for path in paths: |
| 71 | + class_name = path.split('/')[-1].split(separator)[0] |
| 72 | + if class_name not in self.classes: |
| 73 | + self.classes.append(class_name) |
| 74 | + self.samples.append([path, self.classes.index(class_name)]) |
| 75 | + else: |
| 76 | + print("You need a separator with classication datasets", file=sys.stderr) |
| 77 | + return |
| 78 | + else: |
| 79 | + samples_index = dict() |
| 80 | + if separator == '/': |
| 81 | + for path in paths: |
| 82 | + components_name=path.split('/')[-2] |
| 83 | + sample_name = path.split('/')[-1].split('.')[-2] |
| 84 | + if sample_name not in samples_index: |
| 85 | + samples_index[sample_name] = len(self.samples) |
| 86 | + self.samples.append([]) |
| 87 | + self.samples[samples_index[sample_name]].append(path) |
| 88 | + elif separator: |
| 89 | + for path in paths: |
| 90 | + components_name = path.split('.')[-2].split(separator)[-1] |
| 91 | + sample_name = path.split('/')[-1].split(separator)[0] |
| 92 | + if sample_name not in samples_index: |
| 93 | + samples_index[sample_name] = len(self.samples) |
| 94 | + self.samples.append([]) |
| 95 | + self.samples[samples_index[sample_name]].append(path) |
| 96 | + else: |
| 97 | + single_folder=True |
| 98 | + file_root=path[:path.rfind("/")] |
| 99 | + for path in paths: |
| 100 | + if not path.startswith(file_root): |
| 101 | + single_folder=False |
| 102 | + break |
| 103 | + if single_folder: |
| 104 | + for path in paths: |
| 105 | + sample_name = path.split('/')[-1].split('.')[-2] |
| 106 | + if sample_name not in samples_index: |
| 107 | + samples_index[sample_name] = len(self.samples) |
| 108 | + self.samples.append([]) |
| 109 | + self.samples[samples_index[sample_name]].append(path) |
| 110 | + else: |
| 111 | + for path in paths: |
| 112 | + components_name = path.split('/')[-1].split('.')[-2] |
| 113 | + sample_name = path.split('/')[-2] |
| 114 | + if sample_name not in samples_index: |
| 115 | + samples_index[sample_name] = len(self.samples) |
| 116 | + self.samples.append([]) |
| 117 | + self.samples[samples_index[sample_name]].append(path) |
| 118 | + |
| 119 | + def to_tensors(self, path:str): |
| 120 | + if path.endswith('.jpg') or path.endswith('.jpeg') or path.endswith('.png'): |
| 121 | + img=Image.open(path) |
| 122 | + if img.getpalette(): |
| 123 | + return [torch.from_numpy(np.array(img, dtype=np.uint8))] |
| 124 | + else: |
| 125 | + trans=torchvision.transforms.ToTensor() |
| 126 | + return [trans(img)] |
| 127 | + |
| 128 | + if path.endswith('.mp3') or path.endswith('.wav'): |
| 129 | + waveform, sample_rate = torchaudio.load(path) |
| 130 | + return [waveform] |
| 131 | + |
| 132 | + if path.endswith('.npy') or path.endswith('.npz'): |
| 133 | + arrays = np.load(path) |
| 134 | + if type(arrays) == dict: |
| 135 | + tensors = [] |
| 136 | + for array in arrays: |
| 137 | + tensors.append(torch.from_numpy(arrays[array])) |
| 138 | + return tensors |
| 139 | + else: |
| 140 | + return [torch.from_numpy(arrays)] |
| 141 | + |
| 142 | + def __len__(self): |
| 143 | + return len(self.samples) |
| 144 | + |
| 145 | + def __getitem__(self, id): |
| 146 | + """ |
| 147 | + Returns: |
| 148 | + A tuple of tensors. |
| 149 | + """ |
| 150 | + |
| 151 | + if id < 0 or id >= len(self): |
| 152 | + raise IndexError |
| 153 | + |
| 154 | + components = [] |
| 155 | + for component in self.samples[id]: |
| 156 | + if type(component) is str: |
| 157 | + components.extend(self.to_tensors(component)) |
| 158 | + else: |
| 159 | + components.extend([torch.tensor(component)]) |
| 160 | + |
| 161 | + if self.transforms: |
| 162 | + if type(self.transforms) is not list and type(self.transforms) is not tuple: |
| 163 | + self.transforms = [self.transforms] |
| 164 | + for i, transform in enumerate(self.transforms): |
| 165 | + if i < len(components) and transform is not None: |
| 166 | + components[i] = transform(components[i]) |
| 167 | + |
| 168 | + return tuple(components) |
0 commit comments