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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import kornia.augmentation as K
|
| 2 |
+
import torch
|
| 3 |
+
from torchgeo.datasets import So2Sat
|
| 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 |
+
import h5py
|
| 11 |
+
from typing import TypeAlias, ClassVar
|
| 12 |
+
import pathlib
|
| 13 |
+
Path: TypeAlias = str | os.PathLike[str]
|
| 14 |
+
|
| 15 |
+
class SenBenchSo2Sat(So2Sat):
|
| 16 |
+
|
| 17 |
+
versions = ('3_culture_10')
|
| 18 |
+
filenames_by_version: ClassVar[dict[str, dict[str, str]]] = {
|
| 19 |
+
# '2': {
|
| 20 |
+
# 'train': 'training.h5',
|
| 21 |
+
# 'validation': 'validation.h5',
|
| 22 |
+
# 'test': 'testing.h5',
|
| 23 |
+
# },
|
| 24 |
+
# '3_random': {'train': 'random/training.h5', 'test': 'random/testing.h5'},
|
| 25 |
+
# '3_block': {'train': 'block/training.h5', 'test': 'block/testing.h5'},
|
| 26 |
+
'3_culture_10': {
|
| 27 |
+
'train': 'culture_10/train-new.h5',
|
| 28 |
+
'val': 'culture_10/val-new.h5',
|
| 29 |
+
'test': 'culture_10/test-new.h5',
|
| 30 |
+
},
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
classes = (
|
| 34 |
+
'Compact high rise',
|
| 35 |
+
'Compact mid rise',
|
| 36 |
+
'Compact low rise',
|
| 37 |
+
'Open high rise',
|
| 38 |
+
'Open mid rise',
|
| 39 |
+
'Open low rise',
|
| 40 |
+
'Lightweight low rise',
|
| 41 |
+
'Large low rise',
|
| 42 |
+
'Sparsely built',
|
| 43 |
+
'Heavy industry',
|
| 44 |
+
'Dense trees',
|
| 45 |
+
'Scattered trees',
|
| 46 |
+
'Bush, scrub',
|
| 47 |
+
'Low plants',
|
| 48 |
+
'Bare rock or paved',
|
| 49 |
+
'Bare soil or sand',
|
| 50 |
+
'Water',
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
all_s1_band_names = (
|
| 54 |
+
'S1_B1', # VH real
|
| 55 |
+
'S1_B2', # VH imaginary
|
| 56 |
+
'S1_B3', # VV real
|
| 57 |
+
'S1_B4', # VV imaginary
|
| 58 |
+
'S1_B5', # VH intensity
|
| 59 |
+
'S1_B6', # VV intensity
|
| 60 |
+
'S1_B7', # PolSAR covariance matrix off-diagonal real
|
| 61 |
+
'S1_B8', # PolSAR covariance matrix off-diagonal imaginary
|
| 62 |
+
)
|
| 63 |
+
all_s2_band_names = (
|
| 64 |
+
'S2_B02',
|
| 65 |
+
'S2_B03',
|
| 66 |
+
'S2_B04',
|
| 67 |
+
'S2_B05',
|
| 68 |
+
'S2_B06',
|
| 69 |
+
'S2_B07',
|
| 70 |
+
'S2_B08',
|
| 71 |
+
'S2_B8A',
|
| 72 |
+
'S2_B11',
|
| 73 |
+
'S2_B12',
|
| 74 |
+
)
|
| 75 |
+
all_band_names = all_s1_band_names + all_s2_band_names
|
| 76 |
+
|
| 77 |
+
rgb_bands = ('S2_B04', 'S2_B03', 'S2_B02')
|
| 78 |
+
|
| 79 |
+
BAND_SETS: ClassVar[dict[str, tuple[str, ...]]] = {
|
| 80 |
+
'all': all_band_names,
|
| 81 |
+
's1': all_s1_band_names,
|
| 82 |
+
's2': all_s2_band_names,
|
| 83 |
+
'rgb': rgb_bands,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
root: Path = 'data',
|
| 89 |
+
version: str = '3_culture_10', # only supported version now
|
| 90 |
+
split: str = 'train',
|
| 91 |
+
bands: Sequence[str] = BAND_SETS['s2'], # only supported bands now
|
| 92 |
+
transforms: Callable[[dict[str, Tensor]], dict[str, Tensor]] | None = None,
|
| 93 |
+
download: bool = False,
|
| 94 |
+
) -> None:
|
| 95 |
+
|
| 96 |
+
#h5py = lazy_import('h5py')
|
| 97 |
+
|
| 98 |
+
assert version in self.versions
|
| 99 |
+
assert split in self.filenames_by_version[version]
|
| 100 |
+
|
| 101 |
+
self._validate_bands(bands)
|
| 102 |
+
self.s1_band_indices: np.typing.NDArray[np.int_] = np.array(
|
| 103 |
+
[
|
| 104 |
+
self.all_s1_band_names.index(b)
|
| 105 |
+
for b in bands
|
| 106 |
+
if b in self.all_s1_band_names
|
| 107 |
+
]
|
| 108 |
+
).astype(int)
|
| 109 |
+
|
| 110 |
+
self.s1_band_names = [self.all_s1_band_names[i] for i in self.s1_band_indices]
|
| 111 |
+
|
| 112 |
+
self.s2_band_indices: np.typing.NDArray[np.int_] = np.array(
|
| 113 |
+
[
|
| 114 |
+
self.all_s2_band_names.index(b)
|
| 115 |
+
for b in bands
|
| 116 |
+
if b in self.all_s2_band_names
|
| 117 |
+
]
|
| 118 |
+
).astype(int)
|
| 119 |
+
|
| 120 |
+
self.s2_band_names = [self.all_s2_band_names[i] for i in self.s2_band_indices]
|
| 121 |
+
|
| 122 |
+
self.bands = bands
|
| 123 |
+
|
| 124 |
+
self.root = root
|
| 125 |
+
self.version = version
|
| 126 |
+
self.split = split
|
| 127 |
+
self.transforms = transforms
|
| 128 |
+
# self.checksum = checksum
|
| 129 |
+
|
| 130 |
+
self.fn = os.path.join(self.root, self.filenames_by_version[version][split])
|
| 131 |
+
|
| 132 |
+
# if not self._check_integrity():
|
| 133 |
+
# raise DatasetNotFoundError(self)
|
| 134 |
+
|
| 135 |
+
with h5py.File(self.fn, 'r') as f:
|
| 136 |
+
self.size: int = f['label'].shape[0]
|
| 137 |
+
|
| 138 |
+
self.patch_area = (16*10/1000)**2 # patchsize 16 pix, gsd 10m
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def __getitem__(self, index: int) -> dict[str, Tensor]:
|
| 142 |
+
"""Return an index within the dataset.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
index: index to return
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
data and label at that index
|
| 149 |
+
"""
|
| 150 |
+
#h5py = lazy_import('h5py')
|
| 151 |
+
with h5py.File(self.fn, 'r') as f:
|
| 152 |
+
#s1 = f['sen1'][index].astype(np.float32)
|
| 153 |
+
#s1 = np.take(s1, indices=self.s1_band_indices, axis=2)
|
| 154 |
+
s2 = f['sen2'][index].astype(np.float32)
|
| 155 |
+
s2 = np.take(s2, indices=self.s2_band_indices, axis=2)
|
| 156 |
+
|
| 157 |
+
# convert one-hot encoding to int64 then torch int
|
| 158 |
+
label = torch.tensor(f['label'][index].argmax())
|
| 159 |
+
|
| 160 |
+
#s1 = np.rollaxis(s1, 2, 0) # convert to CxHxW format
|
| 161 |
+
s2 = np.rollaxis(s2, 2, 0) # convert to CxHxW format
|
| 162 |
+
|
| 163 |
+
#s1 = torch.from_numpy(s1)
|
| 164 |
+
s2 = torch.from_numpy(s2)
|
| 165 |
+
|
| 166 |
+
meta_info = np.array([np.nan, np.nan, np.nan, self.patch_area]).astype(np.float32)
|
| 167 |
+
|
| 168 |
+
sample = {'image': s2, 'label': label, 'meta': torch.from_numpy(meta_info)}
|
| 169 |
+
|
| 170 |
+
if self.transforms is not None:
|
| 171 |
+
sample = self.transforms(sample)
|
| 172 |
+
|
| 173 |
+
return sample
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class ClsDataAugmentation(torch.nn.Module):
|
| 177 |
+
BAND_STATS = {
|
| 178 |
+
'mean': {
|
| 179 |
+
'B01': 1353.72696296,
|
| 180 |
+
'B02': 1117.20222222,
|
| 181 |
+
'B03': 1041.8842963,
|
| 182 |
+
'B04': 946.554,
|
| 183 |
+
'B05': 1199.18896296,
|
| 184 |
+
'B06': 2003.00696296,
|
| 185 |
+
'B07': 2374.00874074,
|
| 186 |
+
'B08': 2301.22014815,
|
| 187 |
+
'B8A': 2599.78311111,
|
| 188 |
+
'B09': 732.18207407,
|
| 189 |
+
'B10': 12.09952894,
|
| 190 |
+
'B11': 1820.69659259,
|
| 191 |
+
'B12': 1118.20259259,
|
| 192 |
+
#'VV': -12.54847273,
|
| 193 |
+
#'VH': -20.19237134
|
| 194 |
+
},
|
| 195 |
+
'std': {
|
| 196 |
+
'B01': 897.27143653,
|
| 197 |
+
'B02': 736.01759721,
|
| 198 |
+
'B03': 684.77615743,
|
| 199 |
+
'B04': 620.02902871,
|
| 200 |
+
'B05': 791.86263829,
|
| 201 |
+
'B06': 1341.28018273,
|
| 202 |
+
'B07': 1595.39989386,
|
| 203 |
+
'B08': 1545.52915718,
|
| 204 |
+
'B8A': 1750.12066835,
|
| 205 |
+
'B09': 475.11595216,
|
| 206 |
+
'B10': 98.26600935,
|
| 207 |
+
'B11': 1216.48651476,
|
| 208 |
+
'B12': 736.6981037,
|
| 209 |
+
#'VV': 5.25697717,
|
| 210 |
+
#'VH': 5.91150917
|
| 211 |
+
}
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
def __init__(self, split, size, bands):
|
| 215 |
+
super().__init__()
|
| 216 |
+
|
| 217 |
+
mean = []
|
| 218 |
+
std = []
|
| 219 |
+
for band in bands:
|
| 220 |
+
band = band[3:]
|
| 221 |
+
mean.append(self.BAND_STATS['mean'][band])
|
| 222 |
+
std.append(self.BAND_STATS['std'][band])
|
| 223 |
+
mean = torch.Tensor(mean)
|
| 224 |
+
std = torch.Tensor(std)
|
| 225 |
+
|
| 226 |
+
if split == "train":
|
| 227 |
+
self.transform = torch.nn.Sequential(
|
| 228 |
+
K.Normalize(mean=mean, std=std),
|
| 229 |
+
K.Resize(size=size, align_corners=True),
|
| 230 |
+
K.RandomHorizontalFlip(p=0.5),
|
| 231 |
+
K.RandomVerticalFlip(p=0.5),
|
| 232 |
+
)
|
| 233 |
+
else:
|
| 234 |
+
self.transform = torch.nn.Sequential(
|
| 235 |
+
K.Normalize(mean=mean, std=std),
|
| 236 |
+
K.Resize(size=size, align_corners=True),
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
@torch.no_grad()
|
| 240 |
+
def forward(self, batch: dict[str,]):
|
| 241 |
+
"""Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple"""
|
| 242 |
+
x_out = self.transform(batch["image"]).squeeze(0)
|
| 243 |
+
return x_out, batch["label"], batch["meta"]
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class SenBenchSo2SatDataset:
|
| 247 |
+
def __init__(self, config):
|
| 248 |
+
self.dataset_config = config
|
| 249 |
+
self.img_size = (config.image_resolution, config.image_resolution)
|
| 250 |
+
self.root_dir = config.data_path
|
| 251 |
+
self.bands = config.band_names
|
| 252 |
+
self.version = config.version
|
| 253 |
+
|
| 254 |
+
def create_dataset(self):
|
| 255 |
+
train_transform = ClsDataAugmentation(split="train", size=self.img_size, bands=self.bands)
|
| 256 |
+
eval_transform = ClsDataAugmentation(split="test", size=self.img_size, bands=self.bands)
|
| 257 |
+
|
| 258 |
+
dataset_train = SenBenchSo2Sat(
|
| 259 |
+
root=self.root_dir, version=self.version, split="train", bands=self.bands, transforms=train_transform
|
| 260 |
+
)
|
| 261 |
+
dataset_val = SenBenchSo2Sat(
|
| 262 |
+
root=self.root_dir, version=self.version, split="val", bands=self.bands, transforms=eval_transform
|
| 263 |
+
)
|
| 264 |
+
dataset_test = SenBenchSo2Sat(
|
| 265 |
+
root=self.root_dir, version=self.version, split="test", bands=self.bands, transforms=eval_transform
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
return dataset_train, dataset_val, dataset_test
|