wangyi111 commited on
Commit
fee5ef4
·
verified ·
1 Parent(s): b9e2203

Upload 2 files

Browse files
eurosat_s2ms/eurosat_ms.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f3f9fc40485d3f5b05c3a772471e1e8382abd34d92960145064db95afe33c842
3
+ size 2027646683
eurosat_s2ms/senbench_eurosats2_wrapper.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import kornia.augmentation as K
2
+ import torch
3
+ from torchgeo.datasets import EuroSAT
4
+ import os
5
+ from collections.abc import Callable, Sequence
6
+ from torch import Tensor
7
+ import numpy as np
8
+ import rasterio
9
+ from pyproj import Transformer
10
+ from typing import TypeAlias, ClassVar
11
+ import pathlib
12
+ Path: TypeAlias = str | os.PathLike[str]
13
+
14
+ class SenBenchEuroSATS2(EuroSAT):
15
+ url = None
16
+ base_dir = 'all_imgs'
17
+ splits = ('train', 'val', 'test')
18
+ split_filenames: ClassVar[dict[str, str]] = {
19
+ 'train': 'eurosat-train.txt',
20
+ 'val': 'eurosat-val.txt',
21
+ 'test': 'eurosat-test.txt',
22
+ }
23
+ all_band_names = (
24
+ 'B01',
25
+ 'B02',
26
+ 'B03',
27
+ 'B04',
28
+ 'B05',
29
+ 'B06',
30
+ 'B07',
31
+ 'B08',
32
+ 'B09',
33
+ 'B10',
34
+ 'B11',
35
+ 'B12',
36
+ 'B8A',
37
+ )
38
+ rgb_bands = ('B04', 'B03', 'B02')
39
+ BAND_SETS: ClassVar[dict[str, tuple[str, ...]]] = {
40
+ 'all': all_band_names,
41
+ 'rgb': rgb_bands,
42
+ 'all-ssl4eo': ('B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B10', 'B11', 'B12')
43
+ }
44
+
45
+ def __init__(
46
+ self,
47
+ root: Path = 'data',
48
+ split: str = 'train',
49
+ bands: Sequence[str] = BAND_SETS['all-ssl4eo'],
50
+ transforms: Callable[[dict[str, Tensor]], dict[str, Tensor]] | None = None,
51
+ download: bool = False,
52
+ ) -> None:
53
+
54
+ self.root = root
55
+ self.transforms = transforms
56
+ self.download = download
57
+ #self.checksum = checksum
58
+
59
+ assert split in ['train', 'val', 'test']
60
+
61
+ self._validate_bands(bands)
62
+ self.bands = bands
63
+ self.band_indices = [(self.all_band_names.index(b)+1) for b in bands if b in self.all_band_names]
64
+
65
+ self._verify()
66
+
67
+ self.valid_fns = []
68
+ self.classes = []
69
+ with open(os.path.join(self.root, self.split_filenames[split])) as f:
70
+ for fn in f:
71
+ self.valid_fns.append(fn.strip().replace('.jpg', '.tif'))
72
+ cls_name = fn.strip().split('_')[0]
73
+ if cls_name not in self.classes:
74
+ self.classes.append(cls_name)
75
+ self.classes = sorted(self.classes)
76
+
77
+ self.root = os.path.join(self.root, self.base_dir)
78
+ #root_path = pathlib.Path(root,split)
79
+ #self.classes = sorted([d.name for d in root_path.iterdir() if d.is_dir()])
80
+ self.class_to_idx = {cls_name: i for i, cls_name in enumerate(self.classes)}
81
+
82
+ self.patch_area = (16*10/1000)**2 # patchsize 16 pix, gsd 10m
83
+
84
+ def __len__(self):
85
+ return len(self.valid_fns)
86
+
87
+ def __getitem__(self, index):
88
+
89
+ image, coord, label = self._load_image(index)
90
+ meta_info = np.array([coord[0], coord[1], np.nan, self.patch_area]).astype(np.float32)
91
+ sample = {'image': image, 'label': label, 'meta': torch.from_numpy(meta_info)}
92
+
93
+ if self.transforms is not None:
94
+ sample = self.transforms(sample)
95
+
96
+ return sample
97
+
98
+
99
+ def _load_image(self, index):
100
+
101
+ fname = self.valid_fns[index]
102
+ dirname = fname.split('_')[0]
103
+ img_path = os.path.join(self.root, dirname, fname)
104
+ target = self.class_to_idx[dirname]
105
+
106
+ with rasterio.open(img_path) as src:
107
+ image = src.read(self.band_indices).astype('float32')
108
+ cx,cy = src.xy(src.height // 2, src.width // 2)
109
+ if src.crs.to_string() != 'EPSG:4326':
110
+ crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326', always_xy=True)
111
+ lon, lat = crs_transformer.transform(cx,cy)
112
+ else:
113
+ lon, lat = cx, cy
114
+
115
+ return torch.from_numpy(image), (lon,lat), target
116
+
117
+
118
+ class ClsDataAugmentation(torch.nn.Module):
119
+ BAND_STATS = {
120
+ 'mean': {
121
+ 'B01': 1353.72696296,
122
+ 'B02': 1117.20222222,
123
+ 'B03': 1041.8842963,
124
+ 'B04': 946.554,
125
+ 'B05': 1199.18896296,
126
+ 'B06': 2003.00696296,
127
+ 'B07': 2374.00874074,
128
+ 'B08': 2301.22014815,
129
+ 'B8A': 2599.78311111,
130
+ 'B09': 732.18207407,
131
+ 'B10': 12.09952894,
132
+ 'B11': 1820.69659259,
133
+ 'B12': 1118.20259259,
134
+ #'VV': -12.54847273,
135
+ #'VH': -20.19237134
136
+ },
137
+ 'std': {
138
+ 'B01': 897.27143653,
139
+ 'B02': 736.01759721,
140
+ 'B03': 684.77615743,
141
+ 'B04': 620.02902871,
142
+ 'B05': 791.86263829,
143
+ 'B06': 1341.28018273,
144
+ 'B07': 1595.39989386,
145
+ 'B08': 1545.52915718,
146
+ 'B8A': 1750.12066835,
147
+ 'B09': 475.11595216,
148
+ 'B10': 98.26600935,
149
+ 'B11': 1216.48651476,
150
+ 'B12': 736.6981037,
151
+ #'VV': 5.25697717,
152
+ #'VH': 5.91150917
153
+ }
154
+ }
155
+
156
+ def __init__(self, split, size, bands):
157
+ super().__init__()
158
+
159
+ mean = []
160
+ std = []
161
+ for band in bands:
162
+ mean.append(self.BAND_STATS['mean'][band])
163
+ std.append(self.BAND_STATS['std'][band])
164
+ mean = torch.Tensor(mean)
165
+ std = torch.Tensor(std)
166
+
167
+ if split == "train":
168
+ self.transform = torch.nn.Sequential(
169
+ K.Normalize(mean=mean, std=std),
170
+ K.Resize(size=size, align_corners=True),
171
+ K.RandomHorizontalFlip(p=0.5),
172
+ K.RandomVerticalFlip(p=0.5),
173
+ )
174
+ else:
175
+ self.transform = torch.nn.Sequential(
176
+ K.Normalize(mean=mean, std=std),
177
+ K.Resize(size=size, align_corners=True),
178
+ )
179
+
180
+ @torch.no_grad()
181
+ def forward(self, batch: dict[str,]):
182
+ """Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple"""
183
+ x_out = self.transform(batch["image"]).squeeze(0)
184
+ return x_out, batch["label"], batch["meta"]
185
+
186
+
187
+ class SenBenchEuroSATS2Dataset:
188
+ def __init__(self, config):
189
+ self.dataset_config = config
190
+ self.img_size = (config.image_resolution, config.image_resolution)
191
+ self.root_dir = config.data_path
192
+ self.bands = config.band_names
193
+
194
+ def create_dataset(self):
195
+ train_transform = ClsDataAugmentation(split="train", size=self.img_size, bands=self.bands)
196
+ eval_transform = ClsDataAugmentation(split="test", size=self.img_size, bands=self.bands)
197
+
198
+ dataset_train = SenBenchEuroSATS2(
199
+ root=self.root_dir, split="train", bands=self.bands, transforms=train_transform
200
+ )
201
+ dataset_val = SenBenchEuroSATS2(
202
+ root=self.root_dir, split="val", bands=self.bands, transforms=eval_transform
203
+ )
204
+ dataset_test = SenBenchEuroSATS2(
205
+ root=self.root_dir, split="test", bands=self.bands, transforms=eval_transform
206
+ )
207
+
208
+ return dataset_train, dataset_val, dataset_test