dronescapes / dronescapes_reader /dronescapes_representations.py
Meehai's picture
scripts updates and readme
c853138
"""Dronescapes representations -- adds various loading/writing/image showing capabilities to dronescapes tasks"""
from __future__ import annotations
from pathlib import Path
from typing import Callable
import numpy as np
import torch as tr
import flow_vis
from skimage.color import rgb2hsv
from overrides import overrides
from matplotlib.cm import Spectral # pylint: disable=no-name-in-module
from torch.nn import functional as F
try:
from npz_representation import NpzRepresentation
except ImportError:
from .npz_representation import NpzRepresentation
class RGBRepresentation(NpzRepresentation):
def __init__(self, *args, **kwargs):
super().__init__(*args, n_channels=3, **kwargs)
class HSVRepresentation(RGBRepresentation):
@overrides
def load_from_disk(self, path: Path) -> tr.Tensor:
rgb = super().load_from_disk(path)
return tr.from_numpy(rgb2hsv(rgb)).float()
class EdgesRepresentation(NpzRepresentation):
def __init__(self, *args, **kwargs):
super().__init__(*args, n_channels=1, **kwargs)
class DepthRepresentation(NpzRepresentation):
"""DepthRepresentation. Implements depth task-specific stuff, like spectral map for plots."""
def __init__(self, name: str, min_depth: float, max_depth: float, *args, **kwargs):
super().__init__(name, n_channels=1, *args, **kwargs)
self.min_depth = min_depth
self.max_depth = max_depth
@overrides
def load_from_disk(self, path: Path) -> tr.Tensor:
"""Reads the npz data from the disk and transforms it properly"""
res = super().load_from_disk(path)
res_clip = res.clip(self.min_depth, self.max_depth)
return res_clip
@overrides
def plot_fn(self, x: tr.Tensor) -> np.ndarray:
x = x.detach().clip(0, 1).squeeze().cpu().numpy()
_min, _max = np.percentile(x, [1, 95])
x = np.nan_to_num((x - _min) / (_max - _min), False, 0, 0, 0).clip(0, 1)
y: np.ndarray = Spectral(x)[..., 0:3] * 255
return y.astype(np.uint8)
class NormalsRepresentation(NpzRepresentation):
def __init__(self, *args, **kwargs):
super().__init__(*args, n_channels=3, **kwargs)
class SemanticRepresentation(NpzRepresentation):
"""SemanticRepresentation. Implements semantic task-specific stuff, like argmaxing if needed"""
def __init__(self, *args, classes: int | list[str], color_map: list[tuple[int, int, int]], **kwargs):
self.n_classes = len(list(range(classes)) if isinstance(classes, int) else classes)
super().__init__(*args, **kwargs, n_channels=self.n_classes)
self.classes = list(range(classes)) if isinstance(classes, int) else classes
self.color_map = color_map
assert len(color_map) == self.n_classes and self.n_classes > 1, (color_map, self.n_classes)
@overrides
def load_from_disk(self, path: Path) -> tr.Tensor:
res = super().load_from_disk(path)
if len(res.shape) == 3:
assert res.shape[-1] == self.n_classes, f"Expected {self.n_classes} (HxWxC), got {res.shape[-1]}"
res = res.argmax(-1)
assert len(res.shape) == 2, f"Only argmaxed data supported, got: {res.shape}"
res = F.one_hot(res.long(), num_classes=self.n_classes).float()
return res
@overrides
def plot_fn(self, x: tr.Tensor) -> np.ndarray:
x_argmax = x.squeeze().nan_to_num(0).detach().argmax(-1).cpu().numpy()
new_images = np.zeros((*x_argmax.shape, 3), dtype=np.uint8)
for i in range(self.n_classes):
new_images[x_argmax == i] = self.color_map[i]
return new_images
color_map_8classes = [[0, 255, 0], [0, 127, 0], [255, 255, 0], [255, 255, 255],
[255, 0, 0], [0, 0, 255], [0, 255, 255], [127, 127, 63]]
classes_8 = ["land", "forest", "residential", "road", "little-objects", "water", "sky", "hill"]
_tasks: list[NpzRepresentation] = [ # some pre-baked representations
rgb := RGBRepresentation("rgb"),
HSVRepresentation("hsv", dependencies=[rgb]),
EdgesRepresentation("edges_gb"),
DepthRepresentation("depth_sfm_manual202204", min_depth=0, max_depth=300),
DepthRepresentation("depth_ufo", min_depth=0, max_depth=1),
NormalsRepresentation("normals_sfm_manual202204"),
SemanticRepresentation("semantic_segprop8", classes=classes_8, color_map=color_map_8classes),
NpzRepresentation("softseg_gb", 3),
]
dronescapes_task_types: dict[str, NpzRepresentation] = {task.name: task for task in _tasks}