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

Upload 2 files

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