Upload senbench_clouds3_wrapper.py
Browse files
cloud_s3olci/senbench_clouds3_wrapper.py
ADDED
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 SenBenchCloudS3(NonGeoDataset):
|
21 |
+
url = None
|
22 |
+
#base_dir = 'all_imgs'
|
23 |
+
splits = ('train', 'val', 'test')
|
24 |
+
|
25 |
+
split_filenames = {
|
26 |
+
'train': 'train.csv',
|
27 |
+
'val': 'val.csv',
|
28 |
+
'test': 'test.csv',
|
29 |
+
}
|
30 |
+
all_band_names = (
|
31 |
+
'Oa01_radiance', 'Oa02_radiance', 'Oa03_radiance', 'Oa04_radiance', 'Oa05_radiance', 'Oa06_radiance', 'Oa07_radiance',
|
32 |
+
'Oa08_radiance', 'Oa09_radiance', 'Oa10_radiance', 'Oa11_radiance', 'Oa12_radiance', 'Oa13_radiance', 'Oa14_radiance',
|
33 |
+
'Oa15_radiance', 'Oa16_radiance', 'Oa17_radiance', 'Oa18_radiance', 'Oa19_radiance', 'Oa20_radiance', 'Oa21_radiance',
|
34 |
+
)
|
35 |
+
all_band_scale = (
|
36 |
+
0.0139465,0.0133873,0.0121481,0.0115198,0.0100953,0.0123538,0.00879161,
|
37 |
+
0.00876539,0.0095103,0.00773378,0.00675523,0.0071996,0.00749684,0.0086512,
|
38 |
+
0.00526779,0.00530267,0.00493004,0.00549962,0.00502847,0.00326378,0.00324118)
|
39 |
+
rgb_bands = ('Oa08_radiance', 'Oa06_radiance', 'Oa04_radiance')
|
40 |
+
|
41 |
+
Cls_index_binary = {
|
42 |
+
'invalid': 0, # --> 255 should be ignored during training
|
43 |
+
'clear': 1, # --> 0
|
44 |
+
'cloud': 2, # --> 1
|
45 |
+
}
|
46 |
+
|
47 |
+
Cls_index_multi = {
|
48 |
+
'invalid': 0, # --> 255 should be ignored during training
|
49 |
+
'clear': 1, # --> 0
|
50 |
+
'cloud-sure': 2, # --> 1
|
51 |
+
'cloud-ambiguous': 3, # --> 2
|
52 |
+
'cloud shadow': 4, # --> 3
|
53 |
+
'snow and ice': 5, # --> 4
|
54 |
+
}
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
def __init__(
|
59 |
+
self,
|
60 |
+
root: Path = 'data',
|
61 |
+
split: str = 'train',
|
62 |
+
bands: Sequence[str] = all_band_names,
|
63 |
+
mode = 'multi',
|
64 |
+
transforms: Callable[[dict[str, Tensor]], dict[str, Tensor]] | None = None,
|
65 |
+
download: bool = False,
|
66 |
+
) -> None:
|
67 |
+
|
68 |
+
self.root = root
|
69 |
+
self.transforms = transforms
|
70 |
+
self.download = download
|
71 |
+
#self.checksum = checksum
|
72 |
+
|
73 |
+
assert split in ['train', 'val', 'test']
|
74 |
+
|
75 |
+
self.bands = bands
|
76 |
+
self.band_indices = [(self.all_band_names.index(b)+1) for b in bands if b in self.all_band_names]
|
77 |
+
|
78 |
+
self.mode = mode
|
79 |
+
self.img_dir = os.path.join(self.root, 's3_olci')
|
80 |
+
self.label_dir = os.path.join(self.root, 'cloud_'+mode)
|
81 |
+
|
82 |
+
self.split_csv = os.path.join(self.root, self.split_filenames[split])
|
83 |
+
self.fnames = []
|
84 |
+
with open(self.split_csv, 'r') as f:
|
85 |
+
lines = f.readlines()
|
86 |
+
for line in lines:
|
87 |
+
fname = line.strip()
|
88 |
+
self.fnames.append(fname)
|
89 |
+
|
90 |
+
self.reference_date = date(1970, 1, 1)
|
91 |
+
self.patch_area = (8*300/1000)**2 # patchsize 8 pix, gsd 300m
|
92 |
+
|
93 |
+
def __len__(self):
|
94 |
+
return len(self.fnames)
|
95 |
+
|
96 |
+
def __getitem__(self, index):
|
97 |
+
|
98 |
+
images, meta_infos = self._load_image(index)
|
99 |
+
#meta_info = np.array([coord[0], coord[1], np.nan, self.patch_area]).astype(np.float32)
|
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 |
+
fname = self.fnames[index]
|
112 |
+
s3_path = os.path.join(self.img_dir, fname)
|
113 |
+
|
114 |
+
with rasterio.open(s3_path) as src:
|
115 |
+
img = src.read()
|
116 |
+
img[np.isnan(img)] = 0
|
117 |
+
chs = []
|
118 |
+
for b in range(21):
|
119 |
+
ch = img[b]*self.all_band_scale[b]
|
120 |
+
#ch = cv2.resize(ch, (256,256), interpolation=cv2.INTER_CUBIC)
|
121 |
+
chs.append(ch)
|
122 |
+
img = np.stack(chs)
|
123 |
+
img = torch.from_numpy(img).float()
|
124 |
+
|
125 |
+
# get lon, lat
|
126 |
+
cx,cy = src.xy(src.height // 2, src.width // 2)
|
127 |
+
if src.crs.to_string() != 'EPSG:4326':
|
128 |
+
# convert to lon, lat
|
129 |
+
crs_transformer = Transformer.from_crs(src.crs, 'epsg:4326', always_xy=True)
|
130 |
+
lon, lat = crs_transformer.transform(cx,cy)
|
131 |
+
else:
|
132 |
+
lon, lat = cx, cy
|
133 |
+
# get time
|
134 |
+
img_fname = os.path.basename(s3_path)
|
135 |
+
date_str = img_fname.split('____')[1][:8]
|
136 |
+
date_obj = date(int(date_str[:4]), int(date_str[4:6]), int(date_str[6:8]))
|
137 |
+
delta = (date_obj - self.reference_date).days
|
138 |
+
meta_info = np.array([lon, lat, delta, self.patch_area]).astype(np.float32)
|
139 |
+
meta_info = torch.from_numpy(meta_info)
|
140 |
+
|
141 |
+
return img, meta_info
|
142 |
+
|
143 |
+
def _load_target(self, index):
|
144 |
+
|
145 |
+
fname = self.fnames[index]
|
146 |
+
label_path = os.path.join(self.label_dir, fname)
|
147 |
+
|
148 |
+
with rasterio.open(label_path) as src:
|
149 |
+
label = src.read(1)
|
150 |
+
#label = cv2.resize(label, (256,256), interpolation=cv2.INTER_NEAREST) # 0-650
|
151 |
+
label[label==0] = 256
|
152 |
+
label = label - 1
|
153 |
+
labels = torch.from_numpy(label).long()
|
154 |
+
|
155 |
+
return labels
|
156 |
+
|
157 |
+
|
158 |
+
|
159 |
+
class SegDataAugmentation(torch.nn.Module):
|
160 |
+
def __init__(self, split, size):
|
161 |
+
super().__init__()
|
162 |
+
|
163 |
+
mean = torch.Tensor([0.0])
|
164 |
+
std = torch.Tensor([1.0])
|
165 |
+
|
166 |
+
self.norm = K.augmentation.Normalize(mean=mean, std=std)
|
167 |
+
|
168 |
+
if split == "train":
|
169 |
+
self.transform = K.augmentation.AugmentationSequential(
|
170 |
+
K.augmentation.Resize(size=size, align_corners=True),
|
171 |
+
K.augmentation.RandomRotation(degrees=90, p=0.5, align_corners=True),
|
172 |
+
K.augmentation.RandomHorizontalFlip(p=0.5),
|
173 |
+
K.augmentation.RandomVerticalFlip(p=0.5),
|
174 |
+
data_keys=["input", "mask"],
|
175 |
+
)
|
176 |
+
else:
|
177 |
+
self.transform = K.augmentation.AugmentationSequential(
|
178 |
+
K.augmentation.Resize(size=size, align_corners=True),
|
179 |
+
data_keys=["input", "mask"],
|
180 |
+
)
|
181 |
+
|
182 |
+
@torch.no_grad()
|
183 |
+
def forward(self, batch: dict[str,]):
|
184 |
+
"""Torchgeo returns a dictionary with 'image' and 'label' keys, but engine expects a tuple"""
|
185 |
+
x,mask = batch["image"], batch["mask"]
|
186 |
+
x = self.norm(x)
|
187 |
+
x_out, mask_out = self.transform(x, mask)
|
188 |
+
return x_out.squeeze(0), mask_out.squeeze(0).squeeze(0), batch["meta"]
|
189 |
+
|
190 |
+
|
191 |
+
class SenBenchCloudS3Dataset:
|
192 |
+
def __init__(self, config):
|
193 |
+
self.dataset_config = config
|
194 |
+
self.img_size = (config.image_resolution, config.image_resolution)
|
195 |
+
self.root_dir = config.data_path
|
196 |
+
self.bands = config.band_names
|
197 |
+
self.mode = config.mode
|
198 |
+
|
199 |
+
def create_dataset(self):
|
200 |
+
train_transform = SegDataAugmentation(split="train", size=self.img_size)
|
201 |
+
eval_transform = SegDataAugmentation(split="test", size=self.img_size)
|
202 |
+
|
203 |
+
dataset_train = SenBenchCloudS3(
|
204 |
+
root=self.root_dir, split="train", bands=self.bands, mode=self.mode, transforms=train_transform
|
205 |
+
)
|
206 |
+
dataset_val = SenBenchCloudS3(
|
207 |
+
root=self.root_dir, split="val", bands=self.bands, mode=self.mode, transforms=eval_transform
|
208 |
+
)
|
209 |
+
dataset_test = SenBenchCloudS3(
|
210 |
+
root=self.root_dir, split="test", bands=self.bands, mode=self.mode, transforms=eval_transform
|
211 |
+
)
|
212 |
+
|
213 |
+
return dataset_train, dataset_val, dataset_test
|