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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from shapely import wkt
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import tacoreader
|
| 17 |
+
|
| 18 |
+
import logging
|
| 19 |
+
import pdb
|
| 20 |
+
|
| 21 |
+
logging.getLogger("rasterio").setLevel(logging.ERROR)
|
| 22 |
+
Path: TypeAlias = str | os.PathLike[str]
|
| 23 |
+
|
| 24 |
+
class SenBenchCloudS2(NonGeoDataset):
|
| 25 |
+
url = None
|
| 26 |
+
#base_dir = 'all_imgs'
|
| 27 |
+
all_band_names = ('B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B10', 'B11', 'B12')
|
| 28 |
+
|
| 29 |
+
split_filenames = {
|
| 30 |
+
'train': 'cloudsen12-l1c-train.taco',
|
| 31 |
+
'val': 'cloudsen12-l1c-val.taco',
|
| 32 |
+
'test': 'cloudsen12-l1c-test.taco',
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
Cls_index_multi = {
|
| 36 |
+
'clear': 0,
|
| 37 |
+
'thick cloud': 1,
|
| 38 |
+
'thin cloud': 2,
|
| 39 |
+
'cloud shadow': 3,
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
root: Path = 'data',
|
| 47 |
+
split: str = 'train',
|
| 48 |
+
bands: Sequence[str] = all_band_names,
|
| 49 |
+
transforms: Callable[[dict[str, Tensor]], dict[str, Tensor]] | None = None,
|
| 50 |
+
download: bool = False,
|
| 51 |
+
) -> None:
|
| 52 |
+
|
| 53 |
+
self.root = root
|
| 54 |
+
self.transforms = transforms
|
| 55 |
+
self.download = download
|
| 56 |
+
#self.checksum = checksum
|
| 57 |
+
|
| 58 |
+
assert split in ['train', 'val', 'test']
|
| 59 |
+
|
| 60 |
+
self.bands = bands
|
| 61 |
+
self.band_indices = [(self.all_band_names.index(b)+1) for b in bands if b in self.all_band_names]
|
| 62 |
+
|
| 63 |
+
taco_file = os.path.join(root,self.split_filenames[split])
|
| 64 |
+
self.dataset = tacoreader.load(taco_file)
|
| 65 |
+
self.cache = {}
|
| 66 |
+
|
| 67 |
+
# filter corrupted entries
|
| 68 |
+
count = 0
|
| 69 |
+
count_corrupted = 0
|
| 70 |
+
#pdb.set_trace()
|
| 71 |
+
for i in range(len(self.dataset)):
|
| 72 |
+
try:
|
| 73 |
+
sample = self.dataset.read(i)
|
| 74 |
+
s2l1c = sample.read(0) # str
|
| 75 |
+
target = sample.read(1) # str
|
| 76 |
+
coord = sample['stac:centroid'][0] # str
|
| 77 |
+
time_start = sample['stac:time_start'][0] # str
|
| 78 |
+
self.cache[count] = (s2l1c, target, coord, time_start)
|
| 79 |
+
count += 1
|
| 80 |
+
except Exception as e:
|
| 81 |
+
count_corrupted += 1
|
| 82 |
+
self.length = count
|
| 83 |
+
print(split,count,"valid samples.")
|
| 84 |
+
|
| 85 |
+
self.reference_date = date(1970, 1, 1)
|
| 86 |
+
self.patch_area = (16*10/1000)**2 # patchsize 16 pix, gsd 10m
|
| 87 |
+
|
| 88 |
+
def __len__(self):
|
| 89 |
+
return self.length
|
| 90 |
+
|
| 91 |
+
def __getitem__(self, index):
|
| 92 |
+
|
| 93 |
+
#pdb.set_trace()
|
| 94 |
+
|
| 95 |
+
# if index not in self.cache:
|
| 96 |
+
# sample = self.dataset.read(index)
|
| 97 |
+
# s2l1c = sample.read(0) # str
|
| 98 |
+
# target = sample.read(1) # str
|
| 99 |
+
# coord = sample['stac:centroid'][0] # str
|
| 100 |
+
# time_start = sample['stac:time_start'][0] # str
|
| 101 |
+
# self.cache[index] = (s2l1c, target, coord, time_start)
|
| 102 |
+
# else:
|
| 103 |
+
#pdb.set_trace()
|
| 104 |
+
s2l1c, target, coord, time_start = self.cache[index]
|
| 105 |
+
|
| 106 |
+
# Open the files and load data
|
| 107 |
+
with rasterio.open(s2l1c) as src, rasterio.open(target) as dst:
|
| 108 |
+
s2l1c_data = src.read().astype('float32')
|
| 109 |
+
target_data = dst.read(1)
|
| 110 |
+
image = torch.from_numpy(s2l1c_data)
|
| 111 |
+
label = torch.from_numpy(target_data).long()
|
| 112 |
+
|
| 113 |
+
coord = wkt.loads(coord).coords[0]
|
| 114 |
+
date_obj = pd.to_datetime(time_start, unit='s').date()
|
| 115 |
+
delta = (date_obj - self.reference_date).days
|
| 116 |
+
meta_info = np.array([coord[0], coord[1], delta, self.patch_area]).astype(np.float32)
|
| 117 |
+
meta_info = torch.from_numpy(meta_info)
|
| 118 |
+
|
| 119 |
+
sample = {'image': image, 'mask': label, 'meta': meta_info}
|
| 120 |
+
|
| 121 |
+
if self.transforms is not None:
|
| 122 |
+
sample = self.transforms(sample)
|
| 123 |
+
|
| 124 |
+
return sample
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class SegDataAugmentation(torch.nn.Module):
|
| 128 |
+
def __init__(self, split, size, band_stats):
|
| 129 |
+
super().__init__()
|
| 130 |
+
|
| 131 |
+
if band_stats is not None:
|
| 132 |
+
mean = band_stats['mean']
|
| 133 |
+
std = band_stats['std']
|
| 134 |
+
else:
|
| 135 |
+
mean = [0.0]
|
| 136 |
+
std = [1.0]
|
| 137 |
+
|
| 138 |
+
mean = torch.Tensor(mean)
|
| 139 |
+
std = torch.Tensor(std)
|
| 140 |
+
|
| 141 |
+
self.norm = K.augmentation.Normalize(mean=mean, std=std)
|
| 142 |
+
|
| 143 |
+
if split == "train":
|
| 144 |
+
self.transform = K.augmentation.AugmentationSequential(
|
| 145 |
+
K.augmentation.Resize(size=size, align_corners=True),
|
| 146 |
+
K.augmentation.RandomRotation(degrees=90, p=0.5, align_corners=True),
|
| 147 |
+
K.augmentation.RandomHorizontalFlip(p=0.5),
|
| 148 |
+
K.augmentation.RandomVerticalFlip(p=0.5),
|
| 149 |
+
data_keys=["input", "mask"],
|
| 150 |
+
)
|
| 151 |
+
else:
|
| 152 |
+
self.transform = K.augmentation.AugmentationSequential(
|
| 153 |
+
K.augmentation.Resize(size=size, align_corners=True),
|
| 154 |
+
data_keys=["input", "mask"],
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
@torch.no_grad()
|
| 158 |
+
def forward(self, batch: dict[str,]):
|
| 159 |
+
"""Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple"""
|
| 160 |
+
x,mask = batch["image"], batch["mask"]
|
| 161 |
+
x = self.norm(x)
|
| 162 |
+
x_out, mask_out = self.transform(x, mask)
|
| 163 |
+
return x_out.squeeze(0), mask_out.squeeze(0).squeeze(0), batch["meta"]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class SenBenchCloudS2Dataset:
|
| 167 |
+
def __init__(self, config):
|
| 168 |
+
self.dataset_config = config
|
| 169 |
+
self.img_size = (config.image_resolution, config.image_resolution)
|
| 170 |
+
self.root_dir = config.data_path
|
| 171 |
+
self.bands = config.band_names
|
| 172 |
+
self.band_stats = config.band_stats
|
| 173 |
+
|
| 174 |
+
def create_dataset(self):
|
| 175 |
+
train_transform = SegDataAugmentation(split="train", size=self.img_size, band_stats=self.band_stats)
|
| 176 |
+
eval_transform = SegDataAugmentation(split="test", size=self.img_size, band_stats=self.band_stats)
|
| 177 |
+
|
| 178 |
+
dataset_train = SenBenchCloudS2(
|
| 179 |
+
root=self.root_dir, split="train", bands=self.bands, transforms=train_transform
|
| 180 |
+
)
|
| 181 |
+
dataset_val = SenBenchCloudS2(
|
| 182 |
+
root=self.root_dir, split="val", bands=self.bands, transforms=eval_transform
|
| 183 |
+
)
|
| 184 |
+
dataset_test = SenBenchCloudS2(
|
| 185 |
+
root=self.root_dir, split="test", bands=self.bands, transforms=eval_transform
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
return dataset_train, dataset_val, dataset_test
|