|
"""Dronescapes representations -- adds various loading/writing/image showing capabilities to dronescapes tasks""" |
|
from pathlib import Path |
|
import numpy as np |
|
import torch as tr |
|
import flow_vis |
|
from overrides import overrides |
|
from matplotlib.cm import hot |
|
from .multitask_dataset import NpzRepresentation |
|
|
|
class DepthRepresentation(NpzRepresentation): |
|
"""DepthRepresentation. Implements depth task-specific stuff, like hotmap.""" |
|
def __init__(self, *args, min_depth: float, max_depth: float, **kwargs): |
|
super().__init__(*args, **kwargs) |
|
self.min_depth = min_depth |
|
self.max_depth = max_depth |
|
|
|
@overrides |
|
def plot_fn(self, x: tr.Tensor) -> np.ndarray: |
|
x = x.detach().cpu().numpy() |
|
x = np.clip(x, self.min_depth, self.max_depth) |
|
x = np.nan_to_num((x - x.min()) / (x.max() - x.min()), 0) |
|
y = hot(x.squeeze())[..., 0:3] |
|
y = np.uint8(y * 255) |
|
return y |
|
|
|
class OpticalFlowRepresentation(NpzRepresentation): |
|
"""OpticalFlowRepresentation. Implements depth task-specific stuff, like using flow_vis.""" |
|
@overrides |
|
def plot_fn(self, x: tr.Tensor) -> np.ndarray: |
|
return flow_vis.flow_to_color(x.squeeze().nan_to_num(0).detach().cpu().numpy()) |
|
|
|
class SemanticRepresentation(NpzRepresentation): |
|
"""SemanticRepresentation. Implements depth task-specific stuff, like using flow_vis.""" |
|
def __init__(self, *args, classes: int | list[str], color_map: list[tuple[int, int, int]], **kwargs): |
|
super().__init__(*args, **kwargs) |
|
self.classes = list(range(classes)) if isinstance(classes, int) else classes |
|
self.n_classes = len(self.classes) |
|
self.color_map = color_map |
|
assert len(color_map) == self.n_classes, (color_map, self.n_classes) |
|
|
|
@overrides |
|
def load_from_disk(self, path: Path) -> tr.Tensor: |
|
res = super().load_from_disk(path) |
|
assert len(res.shape) == 2, f"Only argmaxed data supported, got: {res.shape}" |
|
return res |
|
|
|
@overrides |
|
def plot_fn(self, x: tr.Tensor) -> np.ndarray: |
|
x = x.squeeze().nan_to_num(0).detach().cpu().numpy() |
|
new_images = np.zeros((*x.shape, 3), dtype=np.uint8) |
|
for i in range(self.n_classes): |
|
new_images[x == i] = self.color_map[i] |
|
return new_images |
|
|