Datasets:

ArXiv:
SSL4EO-L-Benchmark / SSL4EO-L-Benchmark.py
yuxuanw8's picture
Upload SSL4EO-L-Benchmark.py with huggingface_hub
3532fee verified
raw
history blame
7.18 kB
import os
import json
import shutil
import datasets
import tifffile
import pandas as pd
import numpy as np
from torchgeo.datasets.cdl import CDL
from torchgeo.datasets.nlcd import NLCD
CMAPS = {
'nlcd': NLCD.cmap,
'cdl': CDL.cmap,
}
S2_MEAN = [752.40087073, 884.29673756, 1144.16202635, 1297.47289228, 1624.90992062, 2194.6423161, 2422.21248945, 2581.64687018, 2368.51236873, 1805.06846033]
S2_STD = [1108.02887453, 1155.15170768, 1183.6292542, 1368.11351514, 1370.265037, 1355.55390699, 1416.51487101, 1439.3086061, 1455.52084939, 1343.48379601]
subset_names = ["etm_sr_cdl", "etm_sr_nlcd", "etm_toa_cdl", "etm_toa_nlcd", "oli_sr_cdl", "oli_sr_nlcd", "oli_tirs_toa_cdl", "oli_tirs_toa_nlcd"]
num_classes = {
'etm_sr_cdl': 134,
'etm_sr_nlcd': 21,
'etm_toa_cdl': 134,
'etm_toa_nlcd': 21,
'oli_sr_cdl': 134,
'oli_sr_nlcd': 21,
'oli_tirs_toa_cdl': 134,
'oli_tirs_toa_nlcd': 21,
}
num_channels = {
'etm_sr_cdl': 6,
'etm_sr_nlcd': 6,
'etm_toa_cdl': 9,
'etm_toa_nlcd': 9,
'oli_sr_cdl': 7,
'oli_sr_nlcd': 7,
'oli_tirs_toa_cdl': 11,
'oli_tirs_toa_nlcd': 11,
}
MEAN = [0]
STD = [0]
metadata = { # TODO: check if info below is correct or not
'etm_sr_cdl': {"bands":["B1", "B2", "B3", "B4", "B5", "B7"], "channel_wv": [485.0, 560.0, 660.0, 835.0, 1650.0, 2220.0], "mean": MEAN * 6, 'std': STD * 6}, # B6 (Thermal Band) and B8 (Panchromatic Band) are excluded
'etm_sr_nlcd': {"bands":["B1", "B2", "B3", "B4", "B5", "B7"], "channel_wv": [485.0, 560.0, 660.0, 835.0, 1650.0, 2220.0], "mean": MEAN * 6, 'std': STD * 6},
'etm_toa_cdl': {"bands":["B1", "B2", "B3", "B4", "B5", "B6L", "B6H", "B7", "B8"], "channel_wv": [485.0, 560.0, 660.0, 835.0, 1650.0, 10900.0, 10900.0, 2220.0, 710.0], "mean": MEAN * 9, 'std': STD * 9},
'etm_toa_nlcd': {"bands":["B1", "B2", "B3", "B4", "B5", "B6L", "B6H", "B7", "B8"], "channel_wv": [485.0, 560.0, 660.0, 835.0, 1650.0, 10900.0, 10900.0, 2220.0, 710.0], "mean": MEAN * 9, 'std': STD * 9},
'oli_sr_cdl': {"bands":["B1", "B2", "B3", "B4", "B5", "B6", "B7"], "channel_wv": [443.0, 482.0, 562.0, 655.0, 865.0, 1610.0, 2200.0], "mean": MEAN * 7, 'std': STD * 7},
'oli_sr_nlcd': {"bands":["B1", "B2", "B3", "B4", "B5", "B6", "B7"], "channel_wv": [443.0, 482.0, 562.0, 655.0, 865.0, 1610.0, 2200.0], "mean": MEAN * 7, 'std': STD * 7},
'oli_tirs_toa_cdl': {"bands":["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11"], "channel_wv": [443.0, 482.0, 562.0, 655.0, 865.0, 1610.0, 2200.0, 590.0, 1735.0, 10800.0, 12000.0], "mean": MEAN * 11, 'std': STD * 11},
'oli_tirs_toa_nlcd': {"bands":["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10", "B11"], "channel_wv": [443.0, 482.0, 562.0, 655.0, 865.0, 1610.0, 2200.0, 590.0, 1735.0, 10800.0, 12000.0], "mean": MEAN * 11, 'std': STD * 11},
}
class SSL4EOLBenchmarkDataset(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.0.0")
DATA_URL = "https://huggingface.co/datasets/GFM-Bench/SSL4EO-L-Benchmark/resolve/main/SSL4EOLBenchmark.zip"
SIZE = HEIGHT = WIDTH = 264
spatial_resolution = 30
BUILDER_CONFIGS = [datasets.BuilderConfig(name=name) for name in subset_names]
DEFAULT_CONFIG_NAME = "etm_sr_cdl"
def __init__(self, *args, **kwargs):
name = kwargs.get('config_name', None)
print(f"config_name: {name}")
self.NUM_CLASSES = num_classes[name] if name else num_classes['etm_sr_cdl']
self.NUM_CHANNELS = num_channels[name] if name else num_channels['etm_sr_cdl']
self.metadata = metadata[name] if name else metadata['etm_sr_cdl']
product = name.split('_')[-1]
cmap = CMAPS[product]
classes = list(cmap.keys())
self.ordinal_map = np.zeros(max(cmap.keys()) + 1, dtype=np.int64)
for v, k in enumerate(classes):
self.ordinal_map[k] = v
super().__init__(*args, **kwargs)
def _info(self):
metadata = self.metadata
metadata['size'] = self.SIZE
metadata['num_classes'] = self.NUM_CLASSES
metadata['spatial_resolution'] = self.spatial_resolution
return datasets.DatasetInfo(
description=json.dumps(metadata),
features=datasets.Features({
"optical": datasets.Array3D(shape=(self.NUM_CHANNELS, self.HEIGHT, self.WIDTH), dtype="float32"),
"label": datasets.Array2D(shape=(self.HEIGHT, self.WIDTH), dtype="int32"),
"spatial_resolution": datasets.Value("int32"),
}),
)
def _split_generators(self, dl_manager):
if isinstance(self.DATA_URL, list):
downloaded_files = dl_manager.download(self.DATA_URL)
combined_file = os.path.join(dl_manager.download_config.cache_dir, "combined.tar.gz")
with open(combined_file, 'wb') as outfile:
for part_file in downloaded_files:
with open(part_file, 'rb') as infile:
shutil.copyfileobj(infile, outfile)
data_dir = dl_manager.extract(combined_file)
os.remove(combined_file)
else:
data_dir = dl_manager.download_and_extract(self.DATA_URL)
return [
datasets.SplitGenerator(
name="train",
gen_kwargs={
"split": 'train',
"data_dir": data_dir,
},
),
datasets.SplitGenerator(
name="val",
gen_kwargs={
"split": 'val',
"data_dir": data_dir,
},
),
datasets.SplitGenerator(
name="test",
gen_kwargs={
"split": 'test',
"data_dir": data_dir,
},
)
]
def _generate_examples(self, split, data_dir):
spatial_resolution = self.spatial_resolution
data_dir = os.path.join(data_dir, "SSL4EOLBenchmark")
metadata = pd.read_csv(os.path.join(data_dir, f"metadata_{self.config.name}.csv"))
metadata = metadata[metadata["split"] == split].reset_index(drop=True)
for index, row in metadata.iterrows():
optical_path = os.path.join(data_dir, row.optical_path)
optical = self._read_image(optical_path).astype(np.float32) # CxHxW
label_path = os.path.join(data_dir, row.label_path)
label = self._read_image(label_path).astype(np.int32)
label = self.ordinal_map[label]
sample = {
"optical": optical,
"label": label,
"spatial_resolution": spatial_resolution,
}
yield f"{index}", sample
def _read_image(self, image_path):
"""Read tiff image from image_path
Args:
image_path:
Image path to read from
Return:
image:
C, H, W numpy array image
"""
image = tifffile.imread(image_path)
if len(image.shape) == 3:
image = np.transpose(image, (2, 0, 1))
return image