-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata.py
More file actions
159 lines (138 loc) · 4.42 KB
/
data.py
File metadata and controls
159 lines (138 loc) · 4.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
from pathlib import Path
from typing import Tuple
import numpy as np
import torch
from PIL import Image
from torch.utils.data import Dataset, DataLoader
from torchvision.transforms import v2
import lightning as l
class PatachedDataModule(l.LightningDataModule):
"""
parameters
---
dataname and configname: str
local config file or repository name on the huggingface hub
batch: int (default: 32, optional)
batch size
n_train: int or float (default: None, optional)
if specified, use only n_train samples in the train/val process
otherwise, use the default split
"""
def __init__(
self,
batch: int = 2,
path_train: str = None,
path_val: str = None,
path_test: str = None,
**kwargs,
):
super().__init__()
# input parameters
self.batch = batch
# datasets
self.dataset = {
"train": None,
"val": None,
"test": None,
}
self.path = {
"train": path_train,
"val": path_val,
"test": path_test,
}
self.kwargs = kwargs
def prepare_data(self):
# download
pass
def setup(self, stage: str):
# Assign train/val datasets for use in dataloaders
if stage == "fit":
self.dataset["train"] = self.get_dataset("train")
self.dataset["val"] = self.get_dataset("val")
elif stage == "test":
self.dataset["test"] = self.get_dataset("test")
def get_dataset(self, split):
return PatchedImages(root=self.path[split])
def set_dataset(self, split):
"""
split: str
train, val, or test
"""
self.dataset[split] = self.get_dataset(split)
# loaders
def get_dataloader(self, split):
if split == "train":
return self.train_dataloader()
elif split == "val":
return self.val_dataloader()
elif split == "test":
return self.test_dataloader()
def train_dataloader(self):
if self.dataset["train"] is None:
self.set_dataset("train")
return DataLoader(
self.dataset["train"],
batch_size=self.batch,
shuffle=True,
pin_memory=True,
# num_workers=4,
# persistent_workers=True,
# collate_fn=self._collate_fn_train,
)
def val_dataloader(self):
if self.dataset["val"] is None:
self.set_dataset("val")
return DataLoader(
self.dataset["val"],
batch_size=self.batch,
shuffle=False,
pin_memory=True,
# num_workers=1,
# collate_fn=self._collate_fn_val,
)
def test_dataloader(self):
if self.dataset["test"] is None:
self.set_dataset("test")
return DataLoader(
self.dataset["test"],
batch_size=self.batch,
shuffle=False,
pin_memory=True,
# num_workers=1,
# collate_fn=self._collate_fn_test,
)
class PatchedImages(Dataset):
"""
Image shape is (720, 1280, 3) --> (768, 1280, 3) --> 6x10 128x128 patches
"""
def __init__(self, root: str, transform=None):
self.files = sorted(Path(root).iterdir())
self.transform = transform
def __getitem__(self, index: int) -> Tuple[torch.Tensor, np.ndarray, str]:
path = str(self.files[index % len(self.files)])
img = Image.open(path)
img, patches = from_img_to_patches(img)
return img, patches, path
def __len__(self):
return len(self.files)
def from_path_to_patches(path):
img = Image.open(path)
return from_img_to_patches(img)
def from_img_to_patches(img):
"""
img: PIL.Image
"""
img = img.resize((1280, 720))
img = np.array(img)
# expanding the first dimension from 720 to 768
pad = ((24, 24), (0, 0), (0, 0))
# img = np.pad(img, pad, 'constant', constant_values=0) / 255
img = np.pad(img, pad, mode="edge") / 255.0
# from (768, 1280, 3) to (3, 768, 1280)
img = np.transpose(img, (2, 0, 1))
img = torch.from_numpy(img).float()
# from (3, 768, 1280) to (3, 6, 128, 10, 128)
patches = np.reshape(img, (3, 6, 128, 10, 128))
# from (3, 6, 128, 10, 128) to (3, 6, 10, 128, 128)
patches = np.transpose(patches, (0, 1, 3, 2, 4))
return img, patches