|
|
import os |
|
|
import sys |
|
|
import lmdb |
|
|
import gzip |
|
|
import torch |
|
|
import logging |
|
|
import numpy as np |
|
|
from enum import Enum |
|
|
import safetensors.torch |
|
|
from torch.utils.data import Dataset |
|
|
|
|
|
""" |
|
|
tensors = { |
|
|
"center": torch.tensor(center), |
|
|
"wcmap": map_data, |
|
|
"B4": rgbnir_data[0, :, :], |
|
|
"B3": rgbnir_data[1, :, :], |
|
|
"B2": rgbnir_data[2, :, :], |
|
|
"B8": rgbnir_data[3, :, :], |
|
|
"B11": swir_data[0, :, :], |
|
|
"B12": swir_data[1, :, :], |
|
|
"S1VV": s1_data[0, :, :], |
|
|
"S1VH": s1_data[1, :, :], |
|
|
"classprops": torch.tensor(count_classes(map_data)), |
|
|
} |
|
|
""" |
|
|
|
|
|
|
|
|
class Bands(Enum): |
|
|
B2 = "B2" |
|
|
B3 = "B3" |
|
|
B4 = "B4" |
|
|
B8 = "B8" |
|
|
B11 = "B11" |
|
|
B12 = "B12" |
|
|
S1VV = "S1VV" |
|
|
S1VH = "S1VH" |
|
|
RGBNIR = "RGBNIR" |
|
|
SWIR = "SWIR" |
|
|
S1 = "S1" |
|
|
ALL = "ALL" |
|
|
|
|
|
|
|
|
class WCv1LMDBReader(Dataset): |
|
|
def __init__(self, |
|
|
map_lmdb_file: os.PathLike, |
|
|
split: str, |
|
|
return_key=False, |
|
|
readonly=True, |
|
|
lmdb_size_limit=8*1024**3, |
|
|
key_type=str, |
|
|
max_len=-1, |
|
|
return_type=tuple, |
|
|
output_bands: list = [Bands.RGBNIR], |
|
|
transforms=None |
|
|
): |
|
|
super().__init__() |
|
|
self.map_lmdb_file = map_lmdb_file |
|
|
self.env: lmdb.Environment | None = None |
|
|
self.db = None |
|
|
self.return_key = return_key |
|
|
self.logger = logging.getLogger(__name__) |
|
|
self.readonly = readonly |
|
|
self._keys = None |
|
|
self.lmdb_size_limit = lmdb_size_limit |
|
|
self.key_type = key_type |
|
|
self.max_len = max_len |
|
|
self.return_type = return_type |
|
|
|
|
|
self. transforms = transforms |
|
|
self.split = split |
|
|
|
|
|
if split is not None: |
|
|
assert split in ['train', 'val', 'test'], f"unrecignized split type. Expected one of ['train', 'val', 'test'] but got {split}" |
|
|
|
|
|
|
|
|
self.configure_output(output_bands) |
|
|
|
|
|
|
|
|
def configure_output(self, output_bands): |
|
|
output = [] |
|
|
for band in output_bands: |
|
|
if band == Bands.RGBNIR: |
|
|
output += [Bands.B2, Bands.B3, Bands.B4, Bands.B8] |
|
|
elif band == Bands.SWIR: |
|
|
output += [Bands.B11, Bands.B12] |
|
|
elif band == Bands.S1: |
|
|
output += [Bands.S1VV, Bands.S1VH] |
|
|
elif band == Bands.ALL: |
|
|
output = [Bands.B2, Bands.B3, Bands.B4, Bands.B8, |
|
|
Bands.B11, Bands.B12, Bands.S1VV, Bands.S1VH] |
|
|
else: |
|
|
if band not in output: |
|
|
output.append(band) |
|
|
self.output_bands = output |
|
|
|
|
|
def set_transforms(self, transfomrs): |
|
|
self.transforms = transfomrs |
|
|
|
|
|
def set_max_len(self, max_len): |
|
|
self.max_len = max_len |
|
|
self.keys() |
|
|
|
|
|
def open_env(self): |
|
|
try: |
|
|
if self.env is None: |
|
|
self.logger.info( |
|
|
f"Opening LMDB environment at {self.map_lmdb_file} ...") |
|
|
self.env = lmdb.open( |
|
|
self.map_lmdb_file, |
|
|
readonly=self.readonly, |
|
|
lock=not self.readonly, |
|
|
meminit=False, |
|
|
readahead=True, |
|
|
map_size=self.lmdb_size_limit, |
|
|
max_spare_txns=18, |
|
|
max_dbs=3 |
|
|
) |
|
|
if self.split is not None: |
|
|
self.db = self.env.open_db(self.split.encode()) |
|
|
else: |
|
|
self.db = None |
|
|
except Exception as err: |
|
|
raise err |
|
|
|
|
|
def keys(self, update: bool = False): |
|
|
self.open_env() |
|
|
|
|
|
if self._keys is None or update: |
|
|
logging.info("(Re-)Reading keys") |
|
|
with self.env.begin(db=self.db) as txn: |
|
|
self._keys = list(txn.cursor().iternext(values=False)) |
|
|
if self.key_type == str: |
|
|
self._keys = [x.decode() for x in self._keys] |
|
|
elif self.key_type == int: |
|
|
self._keys = [int.from_bytes(x, 'big') for x in self._keys] |
|
|
if self.max_len > 0: |
|
|
idxs = np.random.choice(np.arange(len(self._keys)), self.max_len) |
|
|
self._keys = np.asarray(self._keys)[idxs] |
|
|
return self._keys |
|
|
|
|
|
def _encode_key(self, key): |
|
|
if self.key_type == str: |
|
|
return key.encode() |
|
|
if self.key_type == int: |
|
|
return key.to_bytes(sys.getsizeof(key), 'big') |
|
|
return None |
|
|
|
|
|
def close_env(self): |
|
|
if self.env is not None: |
|
|
self.env.close() |
|
|
self.env = None |
|
|
|
|
|
def update_key(self, key: str, updateData: dict, compress=False) -> bool: |
|
|
try: |
|
|
if self.env is None: |
|
|
self.logger.info("LMDB not yet opened") |
|
|
self.logger.info("Open LMDB") |
|
|
self.open_env() |
|
|
with self.env.begin(write=True, db=self.db) as txn: |
|
|
byte_data = safetensors.torch.save(updateData) |
|
|
if compress: |
|
|
byte_data = gzip.compress(byte_data) |
|
|
status = txn.put(self._encode_key(key), byte_data) |
|
|
return status |
|
|
except Exception as ex: |
|
|
print(ex) |
|
|
self.logger.error(ex) |
|
|
raise ex |
|
|
|
|
|
def delete_key(self, index:str|int): |
|
|
if type(index) == int and self.key_type != int: |
|
|
key = self._keys[index] |
|
|
else: |
|
|
key = index |
|
|
with self.env.begin(write=True, buffers=True, db=self.db) as txn: |
|
|
status = txn.delete(self._encode_key(key)) |
|
|
self.keys() |
|
|
return status |
|
|
|
|
|
def count_classes(self, map: np.ndarray | torch.Tensor,output_type=None) -> np.ndarray | torch.Tensor: |
|
|
"""function to count the class proportions of an segmentation map. |
|
|
|
|
|
Args: |
|
|
map (np.ndarray | torch.Tensor): input map on which the class proportions needs to be counted. Input can be a single map (np.ndarray) or batched tensor of multiple maps (torch.Tensor) |
|
|
|
|
|
Returns: |
|
|
np.ndarray | torch.Tensor: the class proportions of the input map. |
|
|
""" |
|
|
if len(map.shape) == 3: |
|
|
map = map.squeeze() |
|
|
|
|
|
if type(map) == np.ndarray: |
|
|
map = torch.tensor(map, dtype=torch.float32) |
|
|
|
|
|
output = [] |
|
|
num_pixel = map.shape[0] * map.shape[1] |
|
|
|
|
|
for i in range(10, 110, 10): |
|
|
if len(map.shape) == 4: |
|
|
percentage = torch.sum(torch.where(map == i, 1, 0), dim=(1,2,3)) / num_pixel |
|
|
else: |
|
|
percentage = torch.sum(torch.where(map == i, 1, 0)) / num_pixel |
|
|
output.append(percentage) |
|
|
|
|
|
if i == 90: |
|
|
if len(map.shape) == 4: |
|
|
percentage = torch.sum(torch.where(map == i, 1, 0), dim=(1,2,3)) / num_pixel |
|
|
else: |
|
|
percentage = torch.sum(torch.where(map == i, 1, 0)) / num_pixel |
|
|
output.append(percentage) |
|
|
|
|
|
if len(map.shape) == 4: |
|
|
class_props = torch.stack(output, dim=1) |
|
|
class_props.requires_grad = True |
|
|
else: |
|
|
class_props = torch.tensor(output) |
|
|
|
|
|
if type(map) == np.ndarray: |
|
|
return class_props.cpu().detach().numpy() |
|
|
if type(map) == torch.Tensor: |
|
|
if output_type is not None: |
|
|
return class_props.type(dtype=output_type) |
|
|
else: |
|
|
return class_props |
|
|
|
|
|
def __len__(self): |
|
|
if self._keys is None: |
|
|
self.logger.info("keys are not loaded yet") |
|
|
self.logger.info("Loading keys") |
|
|
self.keys() |
|
|
if self.max_len > 0: |
|
|
return self.max_len |
|
|
else: |
|
|
return len(self._keys) |
|
|
|
|
|
def __getitem__(self, index: int | str): |
|
|
assert type(index) == int or type( |
|
|
index) == str, f"index can only be of type int or str. Got {type(index)}" |
|
|
|
|
|
if self.env is None: |
|
|
self.logger.info("LMDB not yet opened") |
|
|
self.logger.info("Open LMDB") |
|
|
try: |
|
|
self.open_env() |
|
|
except Exception as err: |
|
|
raise err |
|
|
|
|
|
key = None |
|
|
with self.env.begin(write=False, buffers=True) as txn: |
|
|
if type(index) == int and self.key_type != int: |
|
|
byte_data = txn.get(self._encode_key(self._keys[index]), db=self.db) |
|
|
key = self._keys[index] |
|
|
else: |
|
|
byte_data = txn.get(self._encode_key(index), db=self.db) |
|
|
key = index |
|
|
magic_number = b'\x1f\x8b' |
|
|
|
|
|
try: |
|
|
|
|
|
if (bytes([byte_data[0], byte_data[1]]) == magic_number): |
|
|
tensor_dict = safetensors.torch.load( |
|
|
gzip.decompress(byte_data)) |
|
|
else: |
|
|
tensor_dict = safetensors.torch.load(bytes(byte_data)) |
|
|
except KeyError as e: |
|
|
print(e) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if "wcmap" in tensor_dict.keys(): |
|
|
num_no_data = torch.where(tensor_dict['wcmap'] == 0, 1, 0) |
|
|
|
|
|
|
|
|
class_values = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100] |
|
|
label = tensor_dict['wcmap'].clone() |
|
|
for i, val in enumerate(class_values): |
|
|
label = torch.where( |
|
|
label == val, i, label) |
|
|
label = torch.nn.functional.one_hot( |
|
|
label.squeeze().type(torch.LongTensor), 11).permute(2, 0, 1) |
|
|
|
|
|
if self.return_key: |
|
|
tensor_dict['key'] = key |
|
|
if self.return_type == dict: |
|
|
return tensor_dict |
|
|
else: |
|
|
bands = [] |
|
|
for band in self.output_bands: |
|
|
bands.append(tensor_dict[band.value]) |
|
|
rs_image = torch.stack(bands, 0).type(torch.float32) |
|
|
|
|
|
if self.transforms is not None: |
|
|
image = self.transforms(rs_image) |
|
|
else: |
|
|
image = rs_image |
|
|
|
|
|
if "classprops" in tensor_dict.keys(): |
|
|
class_props = tensor_dict['classprops'] |
|
|
else: |
|
|
class_props = self.count_classes(tensor_dict['wcmap']) |
|
|
return (image, label, class_props) |
|
|
|