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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import shutil
|
| 4 |
+
import datasets
|
| 5 |
+
import tifffile
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import numpy as np
|
| 9 |
+
import geopandas as gpd
|
| 10 |
+
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
S2_MEAN = [1180.2278549 , 1387.76882557, 1436.67627781, 1773.66437066, 2735.86417202, 3080.12530686, 3223.60015887, 3338.35639825, 2418.01390106, 1630.11250759]
|
| 14 |
+
|
| 15 |
+
S2_STD = [1976.91493068, 1917.02121286, 1996.45123112, 1903.34296117, 1785.08356262, 1796.4477813 , 1811.90019014, 1793.47036145, 1474.46979658, 1309.88416505]
|
| 16 |
+
|
| 17 |
+
class PASTISDataset(datasets.GeneratorBasedBuilder):
|
| 18 |
+
VERSION = datasets.Version("1.0.0")
|
| 19 |
+
|
| 20 |
+
DATA_URL = "https://huggingface.co/datasets/yuxuanw8/PASTIS/resolve/main/PASTIS.zip" # TODO
|
| 21 |
+
|
| 22 |
+
metadata = {
|
| 23 |
+
"s2c": {
|
| 24 |
+
"bands": ["B2", "B3", "B4", "B5", "B6", "B7", "B8", "B8A", "B11", "B12"],
|
| 25 |
+
"channel_wv": [492.4, 559.8, 664.6, 704.1, 740.5, 782.8, 832.8, 864.7, 1613.7, 2202.4],
|
| 26 |
+
"mean": S2_MEAN,
|
| 27 |
+
"std": S2_STD,
|
| 28 |
+
},
|
| 29 |
+
"s1": {
|
| 30 |
+
"bands": None,
|
| 31 |
+
"channel_wv": None,
|
| 32 |
+
"mean": None,
|
| 33 |
+
"std": None
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
SIZE = HEIGHT = WIDTH = 128
|
| 38 |
+
|
| 39 |
+
spatial_resolution = 10
|
| 40 |
+
|
| 41 |
+
NUM_CLASSES = 20 # 0 is background class, and 19 is the void label
|
| 42 |
+
|
| 43 |
+
def __init__(self, reference_date="2018-09-10", **kwargs):
|
| 44 |
+
super().__init__(**kwargs)
|
| 45 |
+
self.reference_date = datetime(*map(int, reference_date.split("-")))
|
| 46 |
+
print(f"reference_date: {reference_date} -> {self.reference_date}")
|
| 47 |
+
|
| 48 |
+
def _split_generators(self, dl_manager):
|
| 49 |
+
if isinstance(self.DATA_URL, list):
|
| 50 |
+
downloaded_files = dl_manager.download(self.DATA_URL)
|
| 51 |
+
combined_file = os.path.join(dl_manager.download_config.cache_dir, "combined.tar.gz")
|
| 52 |
+
with open(combined_file, 'wb') as outfile:
|
| 53 |
+
for part_file in downloaded_files:
|
| 54 |
+
with open(part_file, 'rb') as infile:
|
| 55 |
+
shutil.copyfileobj(infile, outfile)
|
| 56 |
+
data_dir = dl_manager.extract(combined_file)
|
| 57 |
+
os.remove(combined_file)
|
| 58 |
+
else:
|
| 59 |
+
data_dir = dl_manager.download_and_extract(self.DATA_URL)
|
| 60 |
+
|
| 61 |
+
return [
|
| 62 |
+
datasets.SplitGenerator(
|
| 63 |
+
name="train",
|
| 64 |
+
gen_kwargs={
|
| 65 |
+
"split": 'train',
|
| 66 |
+
"data_dir": data_dir,
|
| 67 |
+
},
|
| 68 |
+
),
|
| 69 |
+
datasets.SplitGenerator(
|
| 70 |
+
name="val",
|
| 71 |
+
gen_kwargs={
|
| 72 |
+
"split": 'val',
|
| 73 |
+
"data_dir": data_dir,
|
| 74 |
+
},
|
| 75 |
+
),
|
| 76 |
+
datasets.SplitGenerator(
|
| 77 |
+
name="test",
|
| 78 |
+
gen_kwargs={
|
| 79 |
+
"split": 'test',
|
| 80 |
+
"data_dir": data_dir,
|
| 81 |
+
},
|
| 82 |
+
)
|
| 83 |
+
]
|
| 84 |
+
|
| 85 |
+
def _info(self):
|
| 86 |
+
metadata = self.metadata
|
| 87 |
+
metadata['size'] = self.SIZE
|
| 88 |
+
metadata['num_classes'] = self.NUM_CLASSES
|
| 89 |
+
metadata['spatial_resolution'] = self.spatial_resolution
|
| 90 |
+
return datasets.DatasetInfo(
|
| 91 |
+
description=json.dumps(metadata),
|
| 92 |
+
features=datasets.Features({
|
| 93 |
+
"optical": datasets.Array4D(shape=(61, 10, self.HEIGHT, self.WIDTH), dtype="float32"),
|
| 94 |
+
"label": datasets.Array2D(shape=(self.HEIGHT, self.WIDTH), dtype="int32"),
|
| 95 |
+
"dates": datasets.Sequence(datasets.Value("int32")),
|
| 96 |
+
"sequence_len": datasets.Value("int32"),
|
| 97 |
+
"optical_channel_wv": datasets.Sequence(datasets.Value("float32")),
|
| 98 |
+
"spatial_resolution": datasets.Value("int32"),
|
| 99 |
+
}),
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
def _generate_examples(self, split, data_dir):
|
| 103 |
+
optical_channel_wv = self.metadata["s2c"]["channel_wv"]
|
| 104 |
+
spatial_resolution = self.spatial_resolution
|
| 105 |
+
|
| 106 |
+
data_dir = os.path.join(data_dir, "PASTIS")
|
| 107 |
+
metadata = pd.read_csv(os.path.join(data_dir, "metadata.csv"))
|
| 108 |
+
metadata = metadata[metadata["split"] == split].reset_index(drop=True)
|
| 109 |
+
|
| 110 |
+
self._prepare_meta_patch(data_dir)
|
| 111 |
+
self._prepare_date_tables(data_dir)
|
| 112 |
+
|
| 113 |
+
for index, row in metadata.iterrows():
|
| 114 |
+
id_patch = row.optical_path.replace("DATA_S2/S2_", "").replace(".tif", "")
|
| 115 |
+
optical_path = os.path.join(data_dir, row.optical_path)
|
| 116 |
+
optical = self._read_image(optical_path).astype(np.float32) # TxCxHxW
|
| 117 |
+
sequence_len = optical.shape[0]
|
| 118 |
+
optical = self._pad_sequence(optical) # 61xCxHxW
|
| 119 |
+
|
| 120 |
+
label_path = os.path.join(data_dir, row.label_path) # 3xHxW
|
| 121 |
+
label = tifffile.imread(label_path)[0] # HxW
|
| 122 |
+
|
| 123 |
+
# Retrieve date sequences
|
| 124 |
+
dates = self._get_dates(id_patch=id_patch, sat="S2")
|
| 125 |
+
|
| 126 |
+
sample = {
|
| 127 |
+
"optical": optical,
|
| 128 |
+
"optical_channel_wv": optical_channel_wv,
|
| 129 |
+
"dates": dates,
|
| 130 |
+
"sequence_len": sequence_len,
|
| 131 |
+
"label": label,
|
| 132 |
+
"spatial_resolution": spatial_resolution,
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
yield f"{index}", sample
|
| 136 |
+
|
| 137 |
+
# util functions
|
| 138 |
+
|
| 139 |
+
def _prepare_meta_patch(self, data_dir):
|
| 140 |
+
self.meta_patch = gpd.read_file(os.path.join(data_dir, "metadata.geojson"))
|
| 141 |
+
self.meta_patch.index = self.meta_patch["ID_PATCH"].astype(int)
|
| 142 |
+
self.meta_patch.sort_index(inplace=True)
|
| 143 |
+
|
| 144 |
+
def _prepare_date_tables(self, data_dir):
|
| 145 |
+
self.date_tables = {"S2": None}
|
| 146 |
+
self.date_range = np.array(range(-200, 600))
|
| 147 |
+
for s in ["S2"]:
|
| 148 |
+
dates = self.meta_patch["dates-{}".format(s)]
|
| 149 |
+
date_table = pd.DataFrame(
|
| 150 |
+
index=self.meta_patch.index, columns=self.date_range, dtype=int
|
| 151 |
+
)
|
| 152 |
+
for pid, date_seq in dates.items():
|
| 153 |
+
if type(date_seq) == str:
|
| 154 |
+
date_seq = json.loads(date_seq)
|
| 155 |
+
d = pd.DataFrame().from_dict(date_seq, orient="index")
|
| 156 |
+
d = d[0].apply(
|
| 157 |
+
lambda x: (
|
| 158 |
+
datetime(int(str(x)[:4]), int(str(x)[4:6]), int(str(x)[6:]))
|
| 159 |
+
- self.reference_date
|
| 160 |
+
).days
|
| 161 |
+
)
|
| 162 |
+
date_table.loc[pid, d.values] = 1
|
| 163 |
+
date_table = date_table.fillna(0)
|
| 164 |
+
self.date_tables[s] = {
|
| 165 |
+
index: np.array(list(d.values()))
|
| 166 |
+
for index, d in date_table.to_dict(orient="index").items()
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
def _get_dates(self, id_patch, sat="S2"):
|
| 170 |
+
id_patch = int(id_patch)
|
| 171 |
+
return self.date_range[np.where(self.date_tables[sat][id_patch] == 1)[0]]
|
| 172 |
+
|
| 173 |
+
def _pad_sequence(self, optical):
|
| 174 |
+
padding_size = 61 - optical.shape[0]
|
| 175 |
+
if padding_size == 0:
|
| 176 |
+
return optical
|
| 177 |
+
|
| 178 |
+
pad = np.zeros((padding_size, *optical.shape[1:]))
|
| 179 |
+
padded_optical = np.concatenate((optical, pad), axis=0)
|
| 180 |
+
return padded_optical
|
| 181 |
+
|
| 182 |
+
def _read_image(self, image_path):
|
| 183 |
+
"""Read tiff image from image_path
|
| 184 |
+
Args:
|
| 185 |
+
image_path:
|
| 186 |
+
Image path to read from
|
| 187 |
+
|
| 188 |
+
Return:
|
| 189 |
+
image:
|
| 190 |
+
C, H, W numpy array image
|
| 191 |
+
"""
|
| 192 |
+
image = tifffile.imread(image_path)
|
| 193 |
+
if len(image.shape) == 3:
|
| 194 |
+
image = np.transpose(image, (2, 0, 1))
|
| 195 |
+
|
| 196 |
+
return image
|