wangyi111 commited on
Commit
ceacd49
·
verified ·
1 Parent(s): 870751d

Upload senbench_dfc2020_wrapper.py

Browse files
dfc2020_s1s2/senbench_dfc2020_wrapper.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import kornia as K
2
+ import torch
3
+ from torchgeo.datasets.geo import NonGeoDataset
4
+ import os
5
+ from collections.abc import Callable, Sequence
6
+ from torch import Tensor
7
+ import numpy as np
8
+ import rasterio
9
+ import cv2
10
+ from pyproj import Transformer
11
+ from datetime import date
12
+ from typing import TypeAlias, ClassVar
13
+ import pathlib
14
+
15
+ import logging
16
+
17
+ logging.getLogger("rasterio").setLevel(logging.ERROR)
18
+ Path: TypeAlias = str | os.PathLike[str]
19
+
20
+ class SenBenchDFC2020(NonGeoDataset):
21
+ url = None
22
+ #base_dir = 'all_imgs'
23
+ splits = ('train', 'val', 'test')
24
+
25
+ label_filenames = {
26
+ 'train': 'dfc-train-new.csv',
27
+ 'val': 'dfc-val-new.csv',
28
+ 'test': 'dfc-test-new.csv',
29
+ }
30
+ s1_band_names = (
31
+ 'VV', 'VH'
32
+ )
33
+ s2_band_names = (
34
+ 'B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B10', 'B11', 'B12'
35
+ )
36
+
37
+ rgb_band_names = ('B04', 'B03', 'B02')
38
+
39
+ Cls_index = {
40
+ 'Background': 0, # to be ignored
41
+ 'Forest': 1,
42
+ 'Shrubland': 2,
43
+ 'Savanna': 3, # none, to be ignored
44
+ 'Grassland': 4,
45
+ 'Wetland': 5,
46
+ 'Cropland': 6,
47
+ 'Urban/Built-up': 7,
48
+ 'Snow/Ice': 8, # none, to be ignored
49
+ 'Barren': 9,
50
+ 'Water': 10
51
+ }
52
+
53
+ cls_mapping = {0:255, 1:0, 2:1, 3:255, 4:2, 5:3, 6:4, 7:5, 8:255, 9:6, 10:7} # 8 valid classes
54
+
55
+ def __init__(
56
+ self,
57
+ root: Path = 'data',
58
+ split: str = 'train',
59
+ bands: Sequence[str] = s2_band_names,
60
+ modality = 's2',
61
+ transforms: Callable[[dict[str, Tensor]], dict[str, Tensor]] | None = None,
62
+ download: bool = False,
63
+ ) -> None:
64
+
65
+ self.root = root
66
+ self.transforms = transforms
67
+ self.download = download
68
+ #self.checksum = checksum
69
+
70
+ assert split in ['train', 'val', 'test']
71
+
72
+ self.bands = bands
73
+ self.modality = modality
74
+ if self.modality== 's1':
75
+ self.all_band_names = self.s1_band_names
76
+ else:
77
+ self.all_band_names = self.s2_band_names
78
+ self.band_indices = [(self.all_band_names.index(b)+1) for b in bands if b in self.all_band_names]
79
+
80
+ self.img_dir = os.path.join(self.root, modality)
81
+ self.label_dir = os.path.join(self.root, 'dfc')
82
+
83
+ self.label_csv = os.path.join(self.root, self.label_filenames[split])
84
+ self.label_fnames = []
85
+ with open(self.label_csv, 'r') as f:
86
+ lines = f.readlines()
87
+ for line in lines:
88
+ fname = line.strip()
89
+ self.label_fnames.append(fname)
90
+
91
+ #self.reference_date = date(1970, 1, 1)
92
+ self.patch_area = (16*10/1000)**2 # patchsize 8 pix, gsd 300m
93
+
94
+ def __len__(self):
95
+ return len(self.label_fnames)
96
+
97
+ def __getitem__(self, index):
98
+
99
+ images, meta_infos = self._load_image(index)
100
+ label = self._load_target(index)
101
+ sample = {'image': images, 'mask': label, 'meta': meta_infos}
102
+
103
+ if self.transforms is not None:
104
+ sample = self.transforms(sample)
105
+
106
+ return sample
107
+
108
+
109
+ def _load_image(self, index):
110
+
111
+ label_fname = self.label_fnames[index]
112
+ img_fname = label_fname.replace('dfc',self.modality)
113
+ img_path = os.path.join(self.img_dir, img_fname)
114
+
115
+ with rasterio.open(img_path) as src:
116
+ img = src.read(self.band_indices).astype('float32')
117
+ img = torch.from_numpy(img)
118
+
119
+ # # get lon, lat
120
+ # cx,cy = src.xy(src.height // 2, src.width // 2)
121
+ # if src.crs.to_string() != 'EPSG:4326':
122
+ # # convert to lon, lat
123
+ # crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326', always_xy=True)
124
+ # lon, lat = crs_transformer.transform(cx,cy)
125
+ # else:
126
+ # lon, lat = cx, cy
127
+ # # get time
128
+ # img_fname = os.path.basename(s3_path)
129
+ # date_str = img_fname.split('____')[1][:8]
130
+ # date_obj = date(int(date_str[:4]), int(date_str[4:6]), int(date_str[6:8]))
131
+ # delta = (date_obj - self.reference_date).days
132
+ meta_info = np.array([np.nan, np.nan, np.nan, self.patch_area]).astype(np.float32)
133
+ meta_info = torch.from_numpy(meta_info)
134
+
135
+ return img, meta_info
136
+
137
+ def _load_target(self, index):
138
+
139
+ label_fname = self.label_fnames[index]
140
+ label_path = os.path.join(self.label_dir, label_fname)
141
+
142
+ with rasterio.open(label_path) as src:
143
+ label = src.read(1)
144
+ # label[label==0] = 256
145
+ # label = label - 1
146
+ label_remap = label.copy()
147
+ for orig_label, new_label in self.cls_mapping.items():
148
+ label_remap[label == orig_label] = new_label
149
+
150
+ labels = torch.from_numpy(label_remap).long()
151
+
152
+ return labels
153
+
154
+
155
+
156
+ class SegDataAugmentation(torch.nn.Module):
157
+
158
+ def __init__(self, split, size, band_stats):
159
+ super().__init__()
160
+
161
+ if band_stats is not None:
162
+ mean = band_stats['mean']
163
+ std = band_stats['std']
164
+ else:
165
+ mean = [0.0]
166
+ std = [1.0]
167
+
168
+ mean = torch.Tensor(mean)
169
+ std = torch.Tensor(std)
170
+
171
+ self.norm = K.augmentation.Normalize(mean=mean, std=std)
172
+
173
+ if split == "train":
174
+ self.transform = K.augmentation.AugmentationSequential(
175
+ K.augmentation.Resize(size=size, align_corners=True),
176
+ #K.augmentation.RandomResizedCrop(size=size, scale=(0.8,1.0)),
177
+ K.augmentation.RandomRotation(degrees=90, p=0.5, align_corners=True),
178
+ K.augmentation.RandomHorizontalFlip(p=0.5),
179
+ K.augmentation.RandomVerticalFlip(p=0.5),
180
+ data_keys=["input", "mask"],
181
+ )
182
+ else:
183
+ self.transform = K.augmentation.AugmentationSequential(
184
+ K.augmentation.Resize(size=size, align_corners=True),
185
+ data_keys=["input", "mask"],
186
+ )
187
+
188
+ @torch.no_grad()
189
+ def forward(self, batch: dict[str,]):
190
+ """Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple"""
191
+ x,mask = batch["image"], batch["mask"]
192
+ x = self.norm(x)
193
+ x_out, mask_out = self.transform(x, mask)
194
+ return x_out.squeeze(0), mask_out.squeeze(0).squeeze(0), batch["meta"]
195
+
196
+
197
+ class SenBenchDFC2020Dataset:
198
+ def __init__(self, config):
199
+ self.dataset_config = config
200
+ self.img_size = (config.image_resolution, config.image_resolution)
201
+ self.root_dir = config.data_path
202
+ self.bands = config.band_names
203
+ self.modality = config.modality
204
+ self.band_stats = config.band_stats
205
+
206
+ def create_dataset(self):
207
+ train_transform = SegDataAugmentation(split="train", size=self.img_size, band_stats=self.band_stats)
208
+ eval_transform = SegDataAugmentation(split="test", size=self.img_size, band_stats=self.band_stats)
209
+
210
+ dataset_train = SenBenchDFC2020(
211
+ root=self.root_dir, split="train", bands=self.bands, modality=self.modality, transforms=train_transform
212
+ )
213
+ dataset_val = SenBenchDFC2020(
214
+ root=self.root_dir, split="val", bands=self.bands, modality=self.modality, transforms=eval_transform
215
+ )
216
+ dataset_test = SenBenchDFC2020(
217
+ root=self.root_dir, split="test", bands=self.bands, modality=self.modality, transforms=eval_transform
218
+ )
219
+
220
+ return dataset_train, dataset_val, dataset_test