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
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import datasets
|
| 3 |
+
import numpy as np
|
| 4 |
+
import tifffile
|
| 5 |
+
import skimage.io as io
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from typing import ClassVar
|
| 9 |
+
|
| 10 |
+
class EuroSATConfig(datasets.BuilderConfig):
|
| 11 |
+
all_band_names = (
|
| 12 |
+
'B01',
|
| 13 |
+
'B02',
|
| 14 |
+
'B03',
|
| 15 |
+
'B04',
|
| 16 |
+
'B05',
|
| 17 |
+
'B06',
|
| 18 |
+
'B07',
|
| 19 |
+
'B08',
|
| 20 |
+
'B8A',
|
| 21 |
+
'B09',
|
| 22 |
+
'B10',
|
| 23 |
+
'B11',
|
| 24 |
+
'B12',
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
rgb_bands = ('B04', 'B03', 'B02')
|
| 28 |
+
|
| 29 |
+
BAND_SETS: ClassVar[dict[str, tuple[str, ...]]] = {
|
| 30 |
+
'all': all_band_names,
|
| 31 |
+
'rgb': rgb_bands,
|
| 32 |
+
}
|
| 33 |
+
"""BuilderConfig for EuroSAT"""
|
| 34 |
+
def __init__(self, bands=BAND_SETS['all'], **kwargs):
|
| 35 |
+
super(EuroSATConfig, self).__init__(**kwargs)
|
| 36 |
+
self.bands = bands
|
| 37 |
+
self.band_indices = [self.all_band_names.index(b) for b in bands if b in self.all_band_names].long()
|
| 38 |
+
|
| 39 |
+
class EuroSAT(datasets.GeneratorBasedBuilder):
|
| 40 |
+
VERSION = datasets.Version("1.0.0")
|
| 41 |
+
|
| 42 |
+
BUILDER_CONFIGS = [
|
| 43 |
+
EuroSATConfig(
|
| 44 |
+
name="default",
|
| 45 |
+
description="Default configuration"
|
| 46 |
+
),
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
DEFAULT_CONFIG_NAME = "default"
|
| 50 |
+
|
| 51 |
+
def __init__(self, *args, **kwargs):
|
| 52 |
+
super().__init__(*args, **kwargs)
|
| 53 |
+
if 'config' in kwargs:
|
| 54 |
+
user_config = kwargs['config']
|
| 55 |
+
if isinstance(user_config, dict):
|
| 56 |
+
for key, value in user_config.items():
|
| 57 |
+
if hasattr(self.config, key):
|
| 58 |
+
setattr(self.config, key, value)
|
| 59 |
+
else:
|
| 60 |
+
raise ValueError("check user_config, it should be a dict")
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError("config is not specified in arguments")
|
| 63 |
+
|
| 64 |
+
self.height = 64
|
| 65 |
+
self.width = 64
|
| 66 |
+
self.num_channels = self.config.band_indices.shape[0] # TODO: check out this
|
| 67 |
+
self.labels = [
|
| 68 |
+
"AnnualCrop",
|
| 69 |
+
"Forest",
|
| 70 |
+
"HerbaceousVegetation",
|
| 71 |
+
"Highway",
|
| 72 |
+
"Industrial",
|
| 73 |
+
"Pasture",
|
| 74 |
+
"PermanentCrop",
|
| 75 |
+
"Residential",
|
| 76 |
+
"River",
|
| 77 |
+
"SeaLake",
|
| 78 |
+
]
|
| 79 |
+
# self.label_ids = {label: idx for idx, label in enumerate(self.labels)}
|
| 80 |
+
|
| 81 |
+
def _info(self):
|
| 82 |
+
return datasets.DatasetInfo(
|
| 83 |
+
features=datasets.Features({
|
| 84 |
+
"image": datasets.Array3D(shape=(self.num_channels, self.height, self.width), dtype="float32"),
|
| 85 |
+
"label": datasets.ClassLabel(names=self.labels),
|
| 86 |
+
}),
|
| 87 |
+
supervised_keys=("image", "label")
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def _split_generators(self, dl_manager):
|
| 91 |
+
data_dir = dl_manager.download_and_extract("yuxuanw8/EuroSAT") # TODO: check out the correct address for downloading and extracting
|
| 92 |
+
|
| 93 |
+
return [
|
| 94 |
+
datasets.SplitGenerator(
|
| 95 |
+
name="train",
|
| 96 |
+
gen_kwargs={
|
| 97 |
+
"split_file": os.path.join(data_dir, "eurosat-train.txt"),
|
| 98 |
+
"data_dir": os.path.joint(data_dir, "EuroSAT"),
|
| 99 |
+
},
|
| 100 |
+
),
|
| 101 |
+
datasets.SplitGenerator(
|
| 102 |
+
name="val",
|
| 103 |
+
gen_kwargs={
|
| 104 |
+
"split_file": os.path.join(data_dir, "eurosat-val.txt"),
|
| 105 |
+
"data_dir": os.path.joint(data_dir, "EuroSAT"),
|
| 106 |
+
},
|
| 107 |
+
),
|
| 108 |
+
datasets.SplitGenerator(
|
| 109 |
+
name="test",
|
| 110 |
+
gen_kwargs={
|
| 111 |
+
"split_file": os.path.join(data_dir, "eurosat-test.txt"),
|
| 112 |
+
"data_dir": os.path.joint(data_dir, "EuroSAT"),
|
| 113 |
+
},
|
| 114 |
+
)
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
def _generate_examples(self, split_file, data_dir):
|
| 118 |
+
|
| 119 |
+
"""
|
| 120 |
+
split_file: the filename that lists all data points
|
| 121 |
+
data_dir: directory where the actual data is stored
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
data_dir should be in following structure:
|
| 126 |
+
- EuroSAT
|
| 127 |
+
- AnnualCrop
|
| 128 |
+
- AnnualCrop_1.tif
|
| 129 |
+
- AnnualCrop_2.tif
|
| 130 |
+
- ...
|
| 131 |
+
- Forest
|
| 132 |
+
- Forest_1.tif
|
| 133 |
+
- FOrest_2.tif
|
| 134 |
+
- ...
|
| 135 |
+
- ...
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
with open(split_file, 'r') as f:
|
| 139 |
+
for line in f:
|
| 140 |
+
line = line.strip()
|
| 141 |
+
|
| 142 |
+
file_name = line.replace(".jpg", ".tif")
|
| 143 |
+
label = file_name.split('_')[0]
|
| 144 |
+
data_path = os.path.join(data_dir, label, file_name)
|
| 145 |
+
|
| 146 |
+
img = tifffile.imread(data_path)
|
| 147 |
+
|
| 148 |
+
# permute img from HxWxC to CxHxW
|
| 149 |
+
np.transpose(img, (2, 0, 1))
|
| 150 |
+
|
| 151 |
+
# drop any channels if applicable
|
| 152 |
+
img = np.take(img, indices=self.config.band_indices, axis=0)
|
| 153 |
+
|
| 154 |
+
sample = {
|
| 155 |
+
"image": img.astype(np.float32),
|
| 156 |
+
"label": self.info.features['label'].str2int(label),
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
yield f"{label}_{file_name}", sample
|