dronescapes / dronescapes_reader /npz_representation.py
Meehai's picture
mask2former coco/mapillary
22a896e
raw
history blame
4.09 kB
"""MultiTask representations stored as .npz files on the disk"""
from __future__ import annotations
from pathlib import Path
import numpy as np
import torch as tr
class NpzRepresentation:
"""Generic Task with data read from/saved to npz files. Tries to read data as-is from disk and store it as well"""
def __init__(self, name: str, n_channels: int):
self.name = name
self.n_channels = n_channels
self.classes: list[str] | None = None
self.normalization: str | None = None
self.min: tr.Tensor | None = None
self.max: tr.Tensor | None = None
self.mean: tr.Tensor | None = None
self.std: tr.Tensor | None = None
@property
def is_classification(self) -> bool:
"""if we have self.classes"""
return self.classes is not None
def set_normalization(self, normalization: str, stats: tuple[tr.Tensor, tr.Tensor, tr.Tensor, tr.Tensor]):
"""sets the normalization"""
assert normalization in ("min_max", "standardization"), normalization
assert isinstance(stats, tuple) and len(stats) == 4, stats
self.normalization = normalization
self.min, self.max, self.mean, self.std = stats
def load_from_disk(self, path: Path) -> tr.Tensor:
"""Reads the npz data from the disk and transforms it properly"""
data = np.load(path, allow_pickle=False)
data = data if isinstance(data, np.ndarray) else data["arr_0"] # in case on npz, we need this as well
data = data.astype(np.float32) if np.issubdtype(data.dtype, np.floating) else data # float16 is dangerous
res = tr.from_numpy(data)
res = res.unsqueeze(-1) if len(res.shape) == 2 and self.n_channels == 1 else res # (H, W) in some dph/edges
assert ((res.shape[-1] == self.n_channels and len(res.shape) == 3) or
(len(res.shape) == 2 and self.is_classification)), f"{self.name}: {res.shape} vs {self.n_channels}"
return res
def save_to_disk(self, data: tr.Tensor, path: Path):
"""stores this item to the disk which can then be loaded via `load_from_disk`"""
np.save(path, data.cpu().detach().numpy(), allow_pickle=False)
def plot_fn(self, x: tr.Tensor) -> np.ndarray:
"""very basic implementation of converting this representation to a viewable image. You should overwrite this"""
assert isinstance(x, tr.Tensor), type(x)
assert len(x.shape) == 3, x.shape # guaranteed to be (H, W, C) at this point
x = x.nan_to_num(0).cpu().detach()
if x.shape[-1] != 3:
x = x[..., 0:1]
if x.shape[-1] == 1: # guaranteed to be (H, W, 3) after this if statement hopefully
x = x.repeat(1, 1, 3)
if x.dtype == tr.uint8 or self.is_classification:
return x.numpy()
if self.normalization is not None:
x = (x * self.std + self.mean) if self.normalization == "standardization" else x
x = x * (self.max - self.min) + self.min if self.normalization == "min_max" else x
x = (x * 255) if (self.max <= 1).any() else x
x = x.numpy().astype(np.uint8)
return x
def normalize(self, x: tr.Tensor) -> tr.Tensor:
"""normalizes a data point read with self.load_from_disk(path) using external min/max information"""
assert self.min is not None, "self.statistics must be set from reader before task.normalize(x)"
return ((x.float() - self.min) / (self.max - self.min)).nan_to_num(0, 0, 0).float()
def standardize(self, x: tr.Tensor) -> tr.Tensor:
"""standardizes a data point read with self.load_from_disk(path) using external min/max information"""
assert self.min is not None, "self.statistics must be set from reader before task.normalize(x)"
res = ((x.float() - self.mean) / self.std).nan_to_num(0, 0, 0)
res[(res < -10) | (res > 10)] = 0
return res.float()
def __repr__(self):
return str(self)
def __str__(self):
return f"{str(type(self)).split('.')[-1][0:-2]}({self.name}[{self.n_channels}])"