-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdata.py
More file actions
386 lines (306 loc) · 11.1 KB
/
Copy pathdata.py
File metadata and controls
386 lines (306 loc) · 11.1 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# %%
import glob
import albumentations as albu
import cv2
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
DEFAULT_IMG_SIZE = 320
GOOGLE_DIR = "data/google-goes-contrail"
# %%
# visualization a series of images
def visualize(**images):
n = len(images)
plt.figure(figsize=(n * 5, 5))
for i, (name, image) in enumerate(images.items()):
plt.subplot(1, n, i + 1)
plt.xticks([])
plt.yticks([])
plt.title(" ".join(name.split("_")).title())
plt.imshow(image.squeeze())
plt.tight_layout()
plt.show()
def get_train_augmentation(image_size=DEFAULT_IMG_SIZE):
"""Define augmentation for contrail training images."""
transform = [
albu.ShiftScaleRotate(
scale_limit=0.2,
rotate_limit=180,
shift_limit=0.3,
border_mode=0,
value=0,
p=1,
),
albu.PadIfNeeded(
min_height=image_size,
min_width=image_size,
always_apply=True,
border_mode=0,
value=0,
),
albu.Resize(image_size, image_size),
albu.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.3, p=0.5),
]
return albu.Compose(transform)
def get_val_augmentation(image_size=DEFAULT_IMG_SIZE):
"""Define augmentation for contrail validation images."""
transform = [
albu.ShiftScaleRotate(
scale_limit=0.2,
rotate_limit=180,
shift_limit=0.3,
border_mode=0,
value=0,
p=1,
),
albu.PadIfNeeded(
min_height=image_size,
min_width=image_size,
always_apply=True,
border_mode=0,
value=0,
),
albu.Resize(image_size, image_size),
]
return albu.Compose(transform)
def get_test_augmentation(image_size=DEFAULT_IMG_SIZE):
"""Define augmentation for contrail testing images (pad and resize only)."""
transform = [
albu.PadIfNeeded(
min_height=image_size,
min_width=image_size,
always_apply=True,
border_mode=0,
value=0,
),
albu.Resize(image_size, image_size),
]
return albu.Compose(transform)
def get_preprocessing():
"""Construct preprocessing transform
Return:
transform: albumentations.Compose
"""
def to_tensor(input, **kwargs):
return np.expand_dims(input, 0).astype("float32")
_transform = [
# albu.Lambda(image=smp.encoders.get_preprocessing_fn(ENCODER_NAME)),
albu.Lambda(image=to_tensor, mask=to_tensor),
]
return albu.Compose(_transform)
class BaseDataset:
"""Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation masks folder, Default: None
augmentation (albumentations.Compose): data transfromation pipeline
(e.g. flip, scale, perspective, gamma, etc.)
preprocessing (albumentations.Compose): data preprocessing from pre-trained model
(e.g. normalization, shape manipulation, etc.)
"""
def __init__(
self, image_paths, mask_paths=None, augmentation=None, preprocessing=None
):
self.ids = image_paths
self.image_paths = image_paths
self.has_mask = True if mask_paths is not None else False
if self.has_mask:
self.mask_paths = mask_paths
self.augmentation = augmentation
self.preprocessing = preprocessing
def __getitem__(self, i): ...
def __len__(self):
return len(self.ids)
class OwnDataset(BaseDataset):
"""Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation masks folder, Default: None
augmentation (albumentations.Compose): data transfromation pipeline
(e.g. flip, scale, perspective, gamma, etc.)
preprocessing (albumentations.Compose): data preprocessing from pre-trained model
(e.g. normalization, shape manipulation, etc.)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __getitem__(self, i):
# read image in color
image = cv2.imread(self.image_paths[i], cv2.IMREAD_GRAYSCALE)
if self.has_mask:
# read mask (png) and convert to grayscale
mask = np.amax(cv2.imread(self.mask_paths[i], cv2.IMREAD_UNCHANGED), axis=2)
mask = mask / mask.max()
# apply augmentations
if self.augmentation:
sample = self.augmentation(image=image, mask=mask)
image, mask = sample["image"], sample["mask"]
# apply preprocessing
if self.preprocessing:
sample = self.preprocessing(image=image, mask=mask)
image, mask = sample["image"], sample["mask"]
else:
if self.augmentation:
sample = self.augmentation(image=image)
image = sample["image"]
if self.preprocessing:
sample = self.preprocessing(image=image)
image = sample["image"]
# normalize image
image = (image - image.min()) / (image.max() - image.min())
if self.has_mask:
return image, mask
else:
return image
class GoogleDataset(BaseDataset):
"""Read images, apply augmentation and preprocessing transformations.
Args:
images_dir (str): path to images folder
masks_dir (str): path to segmentation masks folder, Default: None
augmentation (albumentations.Compose): data transfromation pipeline
(e.g. flip, scale, perspective, gamma, etc.)
preprocessing (albumentations.Compose): data preprocessing from pre-trained model
(e.g. normalization, shape manipulation, etc.)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ids = ["/".join(p.split("/")[-2:]) for p in self.image_paths]
def __getitem__(self, i):
band13 = np.load(f"{self.image_paths[i]}/band_13.npy")
band15 = np.load(f"{self.image_paths[i]}/band_15.npy")
image = (band13 - band15)[..., 4]
if self.has_mask:
mask = np.load(f"{self.mask_paths[i]}/human_pixel_masks.npy").squeeze()
# apply augmentations
if self.augmentation:
sample = self.augmentation(image=image, mask=mask)
image, mask = sample["image"], sample["mask"]
# apply preprocessing
if self.preprocessing:
sample = self.preprocessing(image=image, mask=mask)
image, mask = sample["image"], sample["mask"]
else:
if self.augmentation:
sample = self.augmentation(image=image)
image = sample["image"]
if self.preprocessing:
sample = self.preprocessing(image=image)
image = sample["image"]
# normalize image
image = (image - image.min()) / (image.max() - image.min())
if self.has_mask:
return image, mask
else:
return image
def own_dataset(for_training=True):
image_paths = sorted(glob.glob(f"data/goes/**/image/*.png"))
mask_paths = sorted(glob.glob(f"data/goes/**/mask/*.png"))
x_train, x_val, y_train, y_val = train_test_split(
image_paths, mask_paths, test_size=0.3, random_state=42
)
train_dataset = OwnDataset(
x_train,
y_train,
augmentation=get_train_augmentation()
if for_training
else get_test_augmentation(),
preprocessing=get_preprocessing(),
)
val_dataset = OwnDataset(
x_val,
y_val,
augmentation=get_val_augmentation()
if for_training
else get_test_augmentation(),
preprocessing=get_preprocessing(),
)
return train_dataset, val_dataset
def google_dataset(for_training=True, contrail_only=False, threshold=100):
mask_stats = pd.read_csv(f"{GOOGLE_DIR}/mask_stats.csv")
if for_training:
# balance the data
selected_records = pd.concat(
[
mask_stats.query("mask_pixels>200"),
mask_stats.query("mask_pixels<200").sample(2000, random_state=42),
]
)
else:
selected_records = mask_stats
if contrail_only:
selected_records = selected_records.query(f"mask_pixels>{threshold}")
train_records = selected_records.query("tag=='train'").record_id.tolist()
val_records = selected_records.query("tag=='validation'").record_id.tolist()
x_train = y_train = [
p
for p in sorted(glob.glob(f"{GOOGLE_DIR}/*/*"))
if "/".join(p.split("/")[-2:]) in train_records
]
x_val = y_val = [
p
for p in sorted(glob.glob(f"{GOOGLE_DIR}/*/*"))
if "/".join(p.split("/")[-2:]) in val_records
]
train_dataset = GoogleDataset(
x_train,
y_train,
augmentation=(
get_train_augmentation() if for_training else get_test_augmentation()
),
preprocessing=get_preprocessing(),
)
val_dataset = GoogleDataset(
x_val,
y_val,
augmentation=(
get_val_augmentation() if for_training else get_test_augmentation()
),
preprocessing=get_preprocessing(),
)
return train_dataset, val_dataset
# %%
def google_dataset_few_shot(for_training=True, n=50):
mask_stats = pd.read_csv(f"{GOOGLE_DIR}/mask_stats.csv")
df_train = mask_stats.query("tag=='train'")
train_samples = pd.concat(
[
df_train.query("0<mask_pixels<1000").sample(int(n * 0.3), random_state=42),
df_train.query("1000<mask_pixels").sample(int(n * 0.7), random_state=42),
]
)
df_val = mask_stats.query("tag=='validation'")
val_samples = pd.concat(
[
df_val.query("mask_pixels==0").sample(50, random_state=42),
df_val.query("mask_pixels>0").sample(200, random_state=42),
]
)
train_records = train_samples.record_id.tolist()
val_records = val_samples.record_id.tolist()
x_train = y_train = [
p
for p in sorted(glob.glob(f"{GOOGLE_DIR}/*/*"))
if "/".join(p.split("/")[-2:]) in train_records
]
x_val = y_val = [
p
for p in sorted(glob.glob(f"{GOOGLE_DIR}/*/*"))
if "/".join(p.split("/")[-2:]) in val_records
]
train_dataset = GoogleDataset(
x_train,
y_train,
augmentation=(
get_train_augmentation() if for_training else get_test_augmentation()
),
preprocessing=get_preprocessing(),
)
val_dataset = GoogleDataset(
x_val,
y_val,
augmentation=(
get_train_augmentation() if for_training else get_test_augmentation()
),
preprocessing=get_preprocessing(),
)
return train_dataset, val_dataset