Datasets:

ArXiv:
File size: 10,645 Bytes
3532fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2349369
3532fee
 
 
 
 
 
 
 
 
 
45a49ec
 
3532fee
 
 
 
 
 
 
 
 
 
 
45a49ec
 
3532fee
 
 
d84e45e
3532fee
 
3ae32f9
 
 
 
 
 
 
 
45a49ec
 
3532fee
 
 
 
 
 
 
 
 
 
 
0456256
 
 
 
3532fee
e12dca8
3532fee
 
 
0456256
 
 
3532fee
1cd7c81
3532fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0567830
3532fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0567830
3532fee
 
 
45a49ec
 
 
 
 
 
 
 
 
3532fee
 
 
 
 
 
45a49ec
 
 
 
 
 
 
3532fee
 
 
 
 
 
 
0567830
3532fee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45a49ec
 
360d4b1
45a49ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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", "etm_oli_toa_cdl", "etm_oli_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,
    "etm_oli_toa_nlcd": 21,
    "etm_oli_toa_cdl": 134,
}

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,
    "etm_oli_toa_nlcd": 20,
    "etm_oli_toa_cdl": 20,
}

MEAN = [0]
STD = [255]

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},
    "etm_oli_toa_nlcd": {"bands":["B1E", "B2E", "B3E", "B4E", "B5E", "B6LE", "B6HE", "B7E", "B8E", "B1O", "B2O", "B3O", "B4O", "B5O", "B6O", "B7O", "B8O", "B9O", "B10O", "B11O"], "channel_wv": [485.0, 560.0, 660.0, 835.0, 1650.0, 10900.0, 10900.0, 2220.0, 710.0, 443.0, 482.0, 562.0, 655.0, 865.0, 1610.0, 2200.0, 590.0, 1735.0, 10800.0, 12000.0], "mean": MEAN * 20, 'std': STD * 20},
    "etm_oli_toa_cdl": {"bands":["B1E", "B2E", "B3E", "B4E", "B5E", "B6LE", "B6HE", "B7E", "B8E", "B1O", "B2O", "B3O", "B4O", "B5O", "B6O", "B7O", "B8O", "B9O", "B10O", "B11O"], "channel_wv": [485.0, 560.0, 660.0, 835.0, 1650.0, 10900.0, 10900.0, 2220.0, 710.0, 443.0, 482.0, 562.0, 655.0, 865.0, 1610.0, 2200.0, 590.0, 1735.0, 10800.0, 12000.0], "mean": MEAN * 20, 'std': STD * 20},
}

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="default"),
        *[datasets.BuilderConfig(name=name) for name in subset_names]
    ] 

    DEFAULT_CONFIG_NAME = "oli_tirs_toa_nlcd"

    def __init__(self, *args, **kwargs):
        name = kwargs.get('config_name', None)
        self.NUM_CLASSES = num_classes[name] if name and name != "default" else num_classes['oli_tirs_toa_nlcd']
        self.NUM_CHANNELS = num_channels[name] if name and name != "default" else num_channels['oli_tirs_toa_nlcd']
        self.metadata = metadata[name] if name and name != "default" else metadata['oli_tirs_toa_nlcd']

        name = "oli_tirs_toa_nlcd" if name is None or name == "default" else name
        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"),
                "optical_channel_wv": datasets.Sequence(datasets.Value("float32")),
                "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):
        optical_channel_wv = self.metadata["channel_wv"]
        spatial_resolution = self.spatial_resolution

        data_dir = os.path.join(data_dir, "SSL4EOLBenchmark")
        if self.config.name in ["etm_oli_toa_nlcd", "etm_oli_toa_cdl"]:
            product = self.config.name.split('_')[-1] # nlcd / cdl
            metadata_oli = pd.read_csv(os.path.join(data_dir, f"metadata_oli_tirs_toa_{product}.csv"))
            metadata_etm = pd.read_csv(os.path.join(data_dir, f"metadata_etm_toa_{product}.csv"))
        
            metadata = self.sort_and_create_new_csv(metadata_oli, metadata_etm)
        else:
            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

            try:
                optical_path_etm = os.path.join(data_dir, row.optical_path_etm)
                optical_etm = self._read_image(optical_path_etm).astype(np.float32)
                optical = np.concatenate((optical_etm, optical), axis=0)
            except:
                pass

            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,
                "optical_channel_wv": optical_channel_wv,
                "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
    
    def sort_and_create_new_csv(self, metadata_oli, metadata_etm):
        def extract_number(optical_path):
            return optical_path.split('/')[1]
        
        metadata_oli['number'] = metadata_oli['optical_path'].apply(extract_number) # a number
        metadata_etm['number'] = metadata_etm['optical_path'].apply(extract_number) # a number
        
        metadata_oli = metadata_oli.sort_values('number').reset_index(drop=True)
        metadata_etm = metadata_etm.sort_values('number').reset_index(drop=True)
        
        new_rows = []
        
        i, j = 0, 0
        while i < len(metadata_oli) and j < len(metadata_etm):
            if metadata_oli.loc[i, 'number'] == metadata_etm.loc[j, 'number']:
                new_rows.append({
                    'split': metadata_oli.loc[i, 'split'],
                    'optical_path_etm': metadata_etm.loc[j, 'optical_path'],
                    'optical_path': metadata_oli.loc[i, 'optical_path'],
                    'label_path': metadata_oli.loc[i, 'label_path']
                })
                i += 1
                j += 1
            elif metadata_oli.loc[i, 'number'] < metadata_etm.loc[j, 'number']:
                i += 1
            else:
                j += 1
        
        new_df = pd.DataFrame(new_rows, columns=['split', 'optical_path_etm', 'optical_path', 'label_path'])
        return new_df