File size: 9,755 Bytes
de74a3a
 
 
 
 
 
 
 
 
 
f432f84
 
de74a3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cdb4f1
 
de74a3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71137c0
ed4d093
 
 
de74a3a
 
 
4ffe87a
0c2f6d8
 
566bcef
 
de74a3a
 
f432f84
 
de74a3a
 
 
fad204d
de74a3a
 
cfc9587
de74a3a
c651c77
de74a3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import os
import json
import shutil
import string
import tifffile
import datasets

import numpy as np
import pandas as pd

from tqdm import tqdm

class_sets = {
        19: [
            'Urban fabric',
            'Industrial or commercial units',
            'Arable land',
            'Permanent crops',
            'Pastures',
            'Complex cultivation patterns',
            'Land principally occupied by agriculture, with significant areas of'
            ' natural vegetation',
            'Agro-forestry areas',
            'Broad-leaved forest',
            'Coniferous forest',
            'Mixed forest',
            'Natural grassland and sparsely vegetated areas',
            'Moors, heathland and sclerophyllous vegetation',
            'Transitional woodland, shrub',
            'Beaches, dunes, sands',
            'Inland wetlands',
            'Coastal wetlands',
            'Inland waters',
            'Marine waters',
        ],
        43: [
            'Continuous urban fabric',
            'Discontinuous urban fabric',
            'Industrial or commercial units',
            'Road and rail networks and associated land',
            'Port areas',
            'Airports',
            'Mineral extraction sites',
            'Dump sites',
            'Construction sites',
            'Green urban areas',
            'Sport and leisure facilities',
            'Non-irrigated arable land',
            'Permanently irrigated land',
            'Rice fields',
            'Vineyards',
            'Fruit trees and berry plantations',
            'Olive groves',
            'Pastures',
            'Annual crops associated with permanent crops',
            'Complex cultivation patterns',
            'Land principally occupied by agriculture, with significant areas of'
            ' natural vegetation',
            'Agro-forestry areas',
            'Broad-leaved forest',
            'Coniferous forest',
            'Mixed forest',
            'Natural grassland',
            'Moors and heathland',
            'Sclerophyllous vegetation',
            'Transitional woodland/shrub',
            'Beaches, dunes, sands',
            'Bare rock',
            'Sparsely vegetated areas',
            'Burnt areas',
            'Inland marshes',
            'Peatbogs',
            'Salt marshes',
            'Salines',
            'Intertidal flats',
            'Water courses',
            'Water bodies',
            'Coastal lagoons',
            'Estuaries',
            'Sea and ocean',
        ],
    }

label_converter = {
        0: 0,
        1: 0,
        2: 1,
        11: 2,
        12: 2,
        13: 2,
        14: 3,
        15: 3,
        16: 3,
        18: 3,
        17: 4,
        19: 5,
        20: 6,
        21: 7,
        22: 8,
        23: 9,
        24: 10,
        25: 11,
        31: 11,
        26: 12,
        27: 12,
        28: 13,
        29: 14,
        33: 15,
        34: 15,
        35: 16,
        36: 16,
        38: 17,
        39: 17,
        40: 18,
        41: 18,
        42: 18,
    }

S2_MEAN = [752.40087073, 884.29673756, 1144.16202635, 1297.47289228, 1624.90992062, 2194.6423161, 2422.21248945, 2517.76053101, 2581.64687018, 2645.51888987, 2368.51236873, 1805.06846033]
S2_STD = [1108.02887453, 1155.15170768, 1183.6292542, 1368.11351514, 1370.265037, 1355.55390699, 1416.51487101, 1474.78900051, 1439.3086061, 1582.28010962, 1455.52084939, 1343.48379601]

S1_MEAN = [-12.54847273, -20.19237134]
S1_STD = [5.25697717, 5.91150917]

parts = [f"a{letter}" for letter in string.ascii_lowercase]
parts.extend([f"b{letter}" for letter in string.ascii_lowercase[:8]]) 

class BigEarthNetDataset(datasets.GeneratorBasedBuilder):
    VERSION = datasets.Version("1.0.0")

    DATA_URL = [
        f"https://huggingface.co/datasets/GFM-Bench/BigEarthNet/resolve/main/data/bigearthnet_part_{part}"
        for part in parts
    ]

    metadata = {
        "s2c": {
            "bands":["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B8A", "B9", "B11", "B12"],
            "channel_wv": [442.7, 492.4, 559.8, 664.6, 704.1, 740.5, 782.8, 832.8, 864.7, 945.1, 1613.7, 2202.4],
            "mean": S2_MEAN,
            "std": S2_STD
        },
        "s1": {
            "bands": ["VV", "VH"],
            "channel_wv": [5500, 5700],
            "mean": S1_MEAN,
            "std": S1_STD
        }
    }

    SIZE = HEIGHT = WIDTH = 120

    NUM_CLASSES = 19

    spatial_resolution = 10

    def __init__(self, *args, **kwargs):
        self.class2idx = {c: i for i, c in enumerate(class_sets[43])}

        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=(12, self.HEIGHT, self.WIDTH), dtype="float32"),
                "radar": datasets.Array3D(shape=(2, self.HEIGHT, self.WIDTH), dtype="float32"),
                "optical_channel_wv": datasets.Sequence(datasets.Value("float32")),
                "radar_channel_wv": datasets.Sequence(datasets.Value("float32")),
                "label": datasets.Sequence(datasets.Value("float32"), length=self.NUM_CLASSES),
                "spatial_resolution": datasets.Value("int32"),
            }),
        )

    def _split_generators(self, dl_manager):
        print(dl_manager.download_config.cache_dir)
        # Ensure cache directory is set
        if dl_manager.download_config.cache_dir is None:
            return []
        if isinstance(self.DATA_URL, list):
            try:
                downloaded_files = dl_manager.download(self.DATA_URL)
                print(f"downloaded files: {downloaded_files}")
                combined_file = os.path.join(dl_manager.download_config.cache_dir, "combined.tar.gz") 
                print(f"copying files to {combined_file}")
                target_dir = os.path.dirname(combined_file)
                os.makedirs(target_dir, exist_ok=True)  # Create only the directory                
                with open(combined_file, 'wb') as outfile:
                    counter = 0 
                    for part_file in tqdm(downloaded_files, desc="Copying files", unit="file"):
                        # print(f"copying {counter}-th file: {part_file}")
                        with open(part_file, 'rb') as infile:
                            shutil.copyfileobj(infile, outfile)
                        counter += 1
                print(f"extacting from {combined_file}")
                data_dir = dl_manager.extract(combined_file)
                os.remove(combined_file)
                print(f"data_dir: {data_dir}")
            except Exception as e:
                print("setting data_dir to None")
                data_dir = None
        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 = np.array(self.metadata["s2c"]["channel_wv"])
        radar_channel_wv = np.array(self.metadata["s1"]["channel_wv"])
        spatial_resolution = self.spatial_resolution

        data_dir = os.path.join(data_dir, "BigEarthNet")
        metadata = pd.read_csv(os.path.join(data_dir, "metadata.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

            radar_path = os.path.join(data_dir, row.radar_path)
            radar = self._read_image(radar_path).astype(np.float32)

            label_path = os.path.join(data_dir, row.label_path)
            label = self._load_label(label_path)

            sample = {
                "optical": optical,
                "radar": radar,
                "optical_channel_wv": optical_channel_wv,
                "radar_channel_wv": radar_channel_wv,
                "label": label,
                "spatial_resolution": spatial_resolution,
            }

            yield f"{index}", sample
    
    def _load_label(self, label_path):
        with open(label_path) as f:
            labels = json.load(f)['labels']
        indices =[self.class2idx[label] for label in labels]
        indices_optional = [label_converter.get(idx) for idx in indices]
        indices = [idx for idx in indices_optional if idx is not None]
        label = np.zeros(19, dtype=np.int64)
        label[indices] = 1
        return label
    
    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)
        image = np.transpose(image, (2, 0, 1))

        return image