wangyi111 commited on
Commit
55a8e59
·
verified ·
1 Parent(s): fe51591

Upload cobench_bigearthnets12_wrapper_csv.py

Browse files
l2_bigearthnet_s1s2/cobench_bigearthnets12_wrapper_csv.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from typing import Callable, Optional
4
+ from collections.abc import Sequence
5
+
6
+ import kornia.augmentation as K
7
+ import pandas as pd
8
+ import rasterio
9
+ import torch
10
+ from torch import Generator, Tensor
11
+ from torch.utils.data import random_split
12
+ from torchgeo.datasets import BigEarthNet
13
+ #from torchgeo.datasets.geo import NonGeoDataset
14
+
15
+ from pyproj import Transformer
16
+ from datetime import date
17
+ import numpy as np
18
+ import pdb
19
+ import ast
20
+
21
+
22
+ class CoBenchBigEarthNetS12(BigEarthNet):
23
+ #url = ''
24
+ splits = ('train', 'val', 'test')
25
+ label_filenames = {
26
+ 'train': 'multilabel-train.csv',
27
+ 'val': 'multilabel-val.csv',
28
+ 'test': 'multilabel-test.csv',
29
+ }
30
+ image_size = (120, 120)
31
+ all_band_names_s1 = ('VV','VH')
32
+ all_band_names_s2 = ('B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B11', 'B12')
33
+
34
+ def __init__(
35
+ self,
36
+ root: str = "data",
37
+ split: str = "train",
38
+ bands: str = "all",
39
+ band_names: Sequence[str] = ('B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B11', 'B12'),
40
+ num_classes: int = 19,
41
+ transforms: Optional[Callable[[dict[str, Tensor]], dict[str, Tensor]]] = None,
42
+ download: bool = False,
43
+ checksum: bool = False,
44
+ ) -> None:
45
+
46
+ assert split in self.splits
47
+ assert bands in ['s1', 's2']
48
+ assert num_classes in [43, 19]
49
+ self.root = root
50
+ self.split = split
51
+ self.bands = bands
52
+ self.num_classes = num_classes
53
+ self.transforms = transforms
54
+
55
+
56
+ self.band_names = band_names
57
+ if self.bands == 's1':
58
+ self.all_band_names = self.all_band_names_s1
59
+ else:
60
+ self.all_band_names = self.all_band_names_s2
61
+ self.band_indices = [(self.all_band_names.index(b)+1) for b in band_names if b in self.all_band_names]
62
+
63
+ self.class2idx_43 = {c: i for i, c in enumerate(self.class_sets[43])}
64
+ self.class2idx_19 = {c: i for i, c in enumerate(self.class_sets[19])}
65
+ #self._verify()
66
+
67
+ #self.folders = self._load_folders()
68
+ self.img_paths = []
69
+ self.labels = []
70
+ self.csv = pd.read_csv(os.path.join(self.root,self.label_filenames[self.split]))
71
+ for i, row in self.csv.iterrows():
72
+ if self.bands == 's1':
73
+ s1_path = os.path.join(self.root, row['s1_path'])
74
+ self.img_paths.append(s1_path)
75
+ elif self.bands == 's2':
76
+ s2_path = os.path.join(self.root, row['s2_path'])
77
+ self.img_paths.append(s2_path)
78
+ labels = row['labels']
79
+ labels_list = ast.literal_eval(labels)
80
+ self.labels.append(labels_list)
81
+
82
+
83
+
84
+ self.patch_area = (16*10/1000)**2
85
+ self.reference_date = date(1970, 1, 1)
86
+
87
+ def __len__(self):
88
+ return len(self.img_paths)
89
+
90
+ def get_class2idx(self, label: str, level=19):
91
+ assert level == 19 or level == 43, "level must be 19 or 43"
92
+ return self.class2idx_19[label] if level == 19 else self.class2idx_43[label]
93
+
94
+ def _load_target(self, index: int) -> Tensor:
95
+ image_labels = self.labels[index]
96
+
97
+ # labels -> indices
98
+ indices = [
99
+ self.get_class2idx(label, level=self.num_classes) for label in image_labels
100
+ ]
101
+
102
+ image_target = torch.zeros(self.num_classes, dtype=torch.long)
103
+ image_target[indices] = 1
104
+
105
+ return image_target
106
+
107
+ def _load_image(self, index: int) -> Tensor:
108
+ path = self.img_paths[index]
109
+ # Bands are of different spatial resolutions
110
+ # Resample to (120, 120)
111
+ with rasterio.open(path) as src:
112
+ array = src.read(
113
+ self.band_indices,
114
+ ).astype('float32')
115
+
116
+ cx,cy = src.xy(src.height // 2, src.width // 2)
117
+ if src.crs.to_string() != 'EPSG:4326':
118
+ crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326', always_xy=True)
119
+ lon, lat = crs_transformer.transform(cx,cy)
120
+ else:
121
+ lon, lat = cx, cy
122
+
123
+ if self.bands == 's1':
124
+ date_str = path.split('/')[-1].split('_')[4]
125
+ else:
126
+ date_str = path.split('/')[-1].split('_')[2]
127
+ date_obj = date(int(date_str[:4]), int(date_str[4:6]), int(date_str[6:8]))
128
+ delta = (date_obj - self.reference_date).days
129
+
130
+ tensor = torch.from_numpy(array).float()
131
+ return tensor, (lon,lat), delta
132
+
133
+ def __getitem__(self, index: int) -> dict[str, Tensor]:
134
+
135
+ image, coord, delta = self._load_image(index)
136
+ meta_info = np.array([coord[0], coord[1], delta, self.patch_area]).astype(np.float32)
137
+ label = self._load_target(index)
138
+ sample: dict[str, Tensor] = {'image': image, 'label': label, 'meta':meta_info}
139
+
140
+ if self.transforms is not None:
141
+ sample = self.transforms(sample)
142
+
143
+ return sample
144
+
145
+
146
+
147
+ class ClsDataAugmentation(torch.nn.Module):
148
+
149
+ def __init__(self, split, size, bands, band_stats):
150
+ super().__init__()
151
+
152
+ self.bands = bands
153
+
154
+ if band_stats is not None:
155
+ mean = band_stats['mean']
156
+ std = band_stats['std']
157
+ else:
158
+ mean = [0.0]
159
+ std = [1.0]
160
+
161
+ mean = torch.Tensor(mean)
162
+ std = torch.Tensor(std)
163
+
164
+ if split == "train":
165
+ self.transform = torch.nn.Sequential(
166
+ K.Normalize(mean=mean, std=std),
167
+ K.Resize(size=size, align_corners=True),
168
+ K.RandomHorizontalFlip(p=0.5),
169
+ K.RandomVerticalFlip(p=0.5),
170
+ )
171
+ else:
172
+ self.transform = torch.nn.Sequential(
173
+ K.Normalize(mean=mean, std=std),
174
+ K.Resize(size=size, align_corners=True),
175
+ )
176
+
177
+ @torch.no_grad()
178
+ def forward(self, sample: dict[str,]):
179
+ """Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple."""
180
+ if self.bands == "rgb":
181
+ sample["image"] = sample["image"][1:4, ...].flip(dims=(0,))
182
+ # get in rgb order and then normalization can be applied
183
+ x_out = self.transform(sample["image"]).squeeze(0)
184
+ return x_out, sample["label"], sample["meta"]
185
+
186
+
187
+ class ClsDataAugmentationSoftCon(torch.nn.Module):
188
+
189
+ def __init__(self, split, size, bands, band_stats):
190
+ super().__init__()
191
+
192
+ self.bands = bands
193
+
194
+ if band_stats is not None:
195
+ self.mean = band_stats['mean']
196
+ self.std = band_stats['std']
197
+ else:
198
+ self.mean = [0.0]
199
+ self.std = [1.0]
200
+
201
+ # mean = torch.Tensor(mean)
202
+ # std = torch.Tensor(std)
203
+
204
+ if split == "train":
205
+ self.transform = torch.nn.Sequential(
206
+ #K.Normalize(mean=mean, std=std),
207
+ K.Resize(size=size, align_corners=True),
208
+ K.RandomHorizontalFlip(p=0.5),
209
+ K.RandomVerticalFlip(p=0.5),
210
+ )
211
+ else:
212
+ self.transform = torch.nn.Sequential(
213
+ #K.Normalize(mean=mean, std=std),
214
+ K.Resize(size=size, align_corners=True),
215
+ )
216
+
217
+ @torch.no_grad()
218
+ def forward(self, sample: dict[str,]):
219
+ """Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple."""
220
+ if self.bands == 's1':
221
+ sample_img = sample["image"]
222
+ ### normalize s1
223
+ self.max_q = torch.quantile(sample_img.reshape(2,-1),0.99,dim=1)
224
+ self.min_q = torch.quantile(sample_img.reshape(2,-1),0.01,dim=1)
225
+ img_bands = []
226
+ for b in range(2):
227
+ img = sample_img[b,:,:].clone()
228
+ ## outlier
229
+ max_q = self.max_q[b]
230
+ min_q = self.min_q[b]
231
+ img = torch.clamp(img, min_q, max_q)
232
+ ## normalize
233
+ img = self.normalize(img,self.mean[b],self.std[b])
234
+ img_bands.append(img)
235
+ sample_img = torch.stack(img_bands,dim=0) # VV,VH (w,h,c)
236
+ elif self.bands == 's2':
237
+ sample_img = sample["image"]
238
+ img_bands = []
239
+ for b in range(12):
240
+ img = sample_img[b,:,:].clone()
241
+ ## normalize
242
+ img = self.normalize(img,self.mean[b],self.std[b])
243
+ img_bands.append(img)
244
+ if b==9:
245
+ # pad zero to B10
246
+ img_bands.append(torch.zeros_like(img))
247
+ sample_img = torch.stack(img_bands,dim=0)
248
+
249
+ x_out = self.transform(sample_img).squeeze(0)
250
+ return x_out, sample["label"], sample["meta"]
251
+
252
+ @torch.no_grad()
253
+ def normalize(self, img, mean, std):
254
+ min_value = mean - 2 * std
255
+ max_value = mean + 2 * std
256
+ img = (img - min_value) / (max_value - min_value)
257
+ img = torch.clamp(img, 0, 1)
258
+ return img
259
+
260
+
261
+ class CoBenchBigEarthNetS12Dataset:
262
+ def __init__(self, config):
263
+ self.dataset_config = config
264
+ self.img_size = (config.image_resolution, config.image_resolution)
265
+ self.root_dir = config.data_path
266
+ self.bands = config.modality
267
+ self.band_names = config.band_names
268
+ self.num_classes = config.num_classes
269
+ self.band_stats = config.band_stats
270
+ self.norm_form = config.norm_form if 'norm_form' in config else None
271
+
272
+ if self.bands == "rgb":
273
+ # start with rgb and extract later
274
+ self.input_bands = "s2"
275
+ else:
276
+ self.input_bands = self.bands
277
+
278
+ def create_dataset(self):
279
+
280
+ if self.norm_form == 'softcon':
281
+ train_transform = ClsDataAugmentationSoftCon(
282
+ split="train", size=self.img_size, bands=self.bands, band_stats=self.band_stats
283
+ )
284
+ eval_transform = ClsDataAugmentationSoftCon(
285
+ split="test", size=self.img_size, bands=self.bands, band_stats=self.band_stats
286
+ )
287
+ else:
288
+ train_transform = ClsDataAugmentation(
289
+ split="train", size=self.img_size, bands=self.bands, band_stats=self.band_stats
290
+ )
291
+ eval_transform = ClsDataAugmentation(
292
+ split="test", size=self.img_size, bands=self.bands, band_stats=self.band_stats
293
+ )
294
+
295
+ dataset_train = CoBenchBigEarthNetS12(
296
+ root=self.root_dir,
297
+ num_classes=self.num_classes,
298
+ split="train",
299
+ bands=self.input_bands,
300
+ band_names=self.band_names,
301
+ transforms=train_transform,
302
+ )
303
+
304
+ # num_subset_samples = int(0.1 * len(dataset_train))
305
+ # # Split the dataset into the subset and the remaining part
306
+ # subset_train, _ = random_split(
307
+ # dataset_train,
308
+ # [num_subset_samples, len(dataset_train) - num_subset_samples],
309
+ # generator=Generator().manual_seed(42),
310
+ # )
311
+
312
+ dataset_val = CoBenchBigEarthNetS12(
313
+ root=self.root_dir,
314
+ num_classes=self.num_classes,
315
+ split="validation",
316
+ bands=self.input_bands,
317
+ band_names=self.band_names,
318
+ transforms=eval_transform,
319
+ )
320
+ dataset_test = CoBenchBigEarthNetS12(
321
+ root=self.root_dir,
322
+ num_classes=self.num_classes,
323
+ split="test",
324
+ bands=self.input_bands,
325
+ band_names=self.band_names,
326
+ transforms=eval_transform,
327
+ )
328
+
329
+ return dataset_train, dataset_val, dataset_test