File size: 2,570 Bytes
fb0cb78 538d2c5 fb0cb78 538d2c5 595564c fb0cb78 5ee88cd be13523 5ee88cd fb0cb78 538d2c5 595564c 538d2c5 fb0cb78 538d2c5 fb0cb78 538d2c5 595564c fb0cb78 595564c fb0cb78 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
"""NEO nodes implementation in ngclib repository"""
from pathlib import Path
import numpy as np
from codecs import encode
from overrides import overrides
import torch as tr
from .multitask_dataset import NpzRepresentation
def _cmap_hex_to_rgb(hex_list):
res = []
for hex_data in hex_list:
r = int(hex_data[1: 3], 16)
g = int(hex_data[3: 5], 16)
b = int(hex_data[5: 7], 16)
res.append([r, g, b])
return np.array(res)
def _act_to_cmap(act_file: Path) -> np.ndarray:
"""converts the .act file to a matplotlib cmap representation"""
with open(act_file, "rb") as act:
raw_data = act.read() # Read binary data
hex_data = encode(raw_data, "hex") # Convert it to hexadecimal values
total_colors_count = int(hex_data[-7:-4], 16) # Get last 3 digits to get number of colors total
total_colors_count = 256
# Decode colors from hex to string and split it by 6 (because colors are #1c1c1c)
colors = [hex_data[i: i + 6].decode() for i in range(0, total_colors_count * 6, 6)]
# Add # to each item and filter empty items if there is a corrupted total_colors_count bit
hex_colors = [f"#{i}" for i in colors if len(i)]
rgb_colors = _cmap_hex_to_rgb(hex_colors)
return rgb_colors
class NEONode(NpzRepresentation):
"""NEO nodes implementation"""
def __init__(self, node_type: str, name: str):
self.node_type = node_type
self.name = name
act_path = Path(__file__).absolute().parent / "cmaps" / f"{self.node_type}.act"
assert act_path.exists(), f"Node type '{node_type}' not valid. No act file found: '{act_path}'"
self.cmap = _act_to_cmap(act_path)
@overrides
def load_from_disk(self, path: Path) -> tr.Tensor:
data = np.load(path, allow_pickle=False)
y = data if isinstance(data, np.ndarray) else data["arr_0"] # in case on npz, we need this as well
y = y[0] if y.shape[0] == 1 else y # pylint: disable=unsubscriptable-object
y = np.expand_dims(y, axis=-1) if len(y.shape) == 2 else y
y[y == 0] = float("nan")
return tr.from_numpy(y).float()
@overrides
def save_to_disk(self, data: tr.Tensor, path: Path):
return super().save_to_disk(data.clip(0, 1), path)
def plot_fn(self, x: tr.Tensor) -> np.ndarray:
y = np.clip(x.cpu().detach().numpy(), 0, 1)
y = y * 255
y[np.isnan(y)] = 255
y = y.astype(np.uint).squeeze()
y_rgb = self.cmap[y].astype(np.uint8)
return y_rgb
|