File size: 10,420 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
from __future__ import annotations

import math
from pathlib import Path
import re
from typing import Any

import numpy as np

LIGHTING_DIR = Path(__file__).resolve().parents[2] / 'configs' / 'dataset' / 'lighting'
ADAPTATIONS = ('none', 'night_appearance_v1')
ROLES = ('dashboard', 'hood', 'object', 'pillar')
GAMMA = 2.2
LUMA = np.array([0.2126, 0.7152, 0.0722], np.float32)


def to_uint8(image: np.ndarray) -> np.ndarray:
    return np.ascontiguousarray(
        np.floor(np.clip(image, 0.0, 1.0) * 255.0 + 0.5), dtype=np.uint8
    )


def compose_dc_baseline(clean: np.ndarray, alpha: np.ndarray, obs: np.ndarray) -> np.ndarray:
    return np.clip((1.0 - alpha[..., None]) * clean + obs, 0.0, 1.0)


def compose_hybrid(clean: np.ndarray, alpha: np.ndarray, obs: np.ndarray, solid_mask: np.ndarray,
                   solid_rgb: np.ndarray) -> np.ndarray:
    baseline = compose_dc_baseline(clean, alpha, obs)
    return np.clip(
        (1.0 - solid_mask[..., None]) * baseline + solid_mask[..., None] * solid_rgb,
        0.0,
        1.0,
    )


def compose_batch(clean_frames: np.ndarray, frame_indices: np.ndarray, layers: dict[str, np.ndarray],
                  lighting: dict | None = None) -> np.ndarray:
    if clean_frames.ndim != 4 or clean_frames.shape[0] != len(frame_indices):
        raise ValueError('clean_frames must be [T,H,W,3] with one index per frame')
    if clean_frames.shape[1:] != layers['solid_rgb'].shape:
        raise ValueError('clean frames and prepared layers have different resolutions')
    if not np.isfinite(clean_frames).all():
        raise ValueError('clean frames contain nonfinite values')
    if lighting is None or lighting.get('adaptation', 'none') == 'none':
        return compose_hybrid(
            clean_frames.astype(np.float32), layers['dc_alpha'], layers['dc_observation_rgb'],
            layers['solid_mask_blend'], layers['solid_rgb'],
        )
    if lighting['adaptation'] != 'night_appearance_v1':
        raise ValueError(f"unsupported lighting adaptation: {lighting['adaptation']}")
    if 'hood_reflect_mask' not in layers:
        raise ValueError('night composition needs the hood_reflect_mask layer')
    frames = clean_frames.astype(np.float32)
    return np.stack([night_frame(frames[i], int(frame_indices[i]), layers, lighting) for i in range(len(frame_indices))])


def _number(value: Any, field: str, low: float, high: float) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not low <= value <= high:
        raise ValueError(f'{field}: expected a finite number in [{low}, {high}]')
    return float(value)


def load_lighting_profile(profile_id: str, directory=LIGHTING_DIR) -> dict[str, Any]:
    import yaml
    if not isinstance(profile_id, str) or not re.fullmatch(r'[A-Za-z0-9_-]+', profile_id):
        raise ValueError('lighting profile_id: expected a safe, nonempty identifier')
    path = Path(directory) / f'{profile_id}.yaml'
    if not path.is_file():
        raise FileNotFoundError(f'lighting profile not found: {path}')
    doc = yaml.safe_load(path.read_text())
    if not isinstance(doc, dict) or doc.get('schema_version') != 1 or doc.get('profile_id') != profile_id:
        raise ValueError(f'{path}: invalid lighting profile header')
    adaptation = doc.get('adaptation')
    if adaptation not in ADAPTATIONS:
        raise ValueError(f'{path}: unsupported adaptation {adaptation!r}')
    expected = {'schema_version', 'profile_id', 'adaptation'}
    if adaptation == 'night_appearance_v1':
        expected |= {'solid', 'observation', 'hood_reflection', 'bloom'}
    if set(doc) != expected:
        raise ValueError(f'{path}: fields {sorted(doc)} != {sorted(expected)}')
    if adaptation == 'night_appearance_v1':
        solid = doc['solid']
        if not isinstance(solid, dict) or set(solid) != {'target_over_scene_mean', 'gain_clip', 'desaturate', 'white_balance_blend',
                                                         'noise_sigma_display', 'noise_seed'}:
            raise ValueError(f'{path}: invalid solid section')
        targets = solid['target_over_scene_mean']
        if not isinstance(targets, dict) or set(targets) != set(ROLES):
            raise ValueError(f'{path}: target_over_scene_mean must name every role')
        for role in ROLES:
            _number(targets[role], f'target_over_scene_mean.{role}', 0.0, 10.0)
        clip = solid['gain_clip']
        if not isinstance(clip, list) or len(clip) != 2 or _number(clip[0], 'gain_clip[0]', 0.0, 10.0) > _number(clip[1], 'gain_clip[1]', 0.0, 10.0):
            raise ValueError(f'{path}: gain_clip must be [low, high]')
        _number(solid['desaturate'], 'desaturate', 0.0, 1.0)
        _number(solid['white_balance_blend'], 'white_balance_blend', 0.0, 1.0)
        _number(solid['noise_sigma_display'], 'noise_sigma_display', 0.0, 0.2)
        if isinstance(solid['noise_seed'], bool) or not isinstance(solid['noise_seed'], int) or solid['noise_seed'] < 0:
            raise ValueError(f'{path}: noise_seed must be a nonnegative integer')
        for section, keys in (('observation', {'gain'}), ('hood_reflection', {'reflectance', 'blur_sigma_px'}),
                              ('bloom', {'threshold_linear', 'blur_sigma_px', 'gain'})):
            value = doc[section]
            if not isinstance(value, dict) or set(value) != keys:
                raise ValueError(f'{path}: invalid {section} section')
            for key in keys:
                _number(value[key], f'{section}.{key}', 0.0, 100.0)
    return doc


def is_identity(profile: dict[str, Any]) -> bool:
    return profile['adaptation'] == 'none'


def lin(x: np.ndarray) -> np.ndarray:
    return np.clip(x, 0.0, 1.0).astype(np.float32) ** np.float32(GAMMA)


def disp(x: np.ndarray) -> np.ndarray:
    return np.clip(x, 0.0, 1.0).astype(np.float32) ** np.float32(1.0 / GAMMA)


def luminance(x: np.ndarray) -> np.ndarray:
    return x @ LUMA


def adapt_layers(layers: dict[str, np.ndarray], role_masks: dict[str, np.ndarray], scene_stats: dict[str, Any],
                 profile: dict[str, Any]) -> tuple[dict[str, np.ndarray], dict[str, Any]]:
    if is_identity(profile):
        raise ValueError('adapt_layers is only defined for adapting profiles')
    solid_cfg = profile['solid']
    solid_mask = layers['solid_mask_hard'].astype(bool)
    solid = lin(layers['solid_rgb'])
    scene_mean = float(scene_stats['mean_luminance'])
    lum = luminance(solid)
    gain_map = np.ones(solid_mask.shape, np.float32)
    assigned = np.zeros(solid_mask.shape, bool)
    gains: dict[str, Any] = {}
    low, high = solid_cfg['gain_clip']
    for role in ROLES:
        mask = role_masks.get(role)
        if mask is None:
            continue
        selected = (mask > 0.5) & solid_mask & ~assigned
        if not selected.any():
            continue
        day_mean = float(max(lum[selected].mean(), 1e-6))
        gain = float(np.clip(solid_cfg['target_over_scene_mean'][role] * scene_mean / day_mean, low, high))
        gains[role] = {'pixels': int(selected.sum()), 'day_mean_luminance': day_mean, 'gain': gain}
        gain_map[selected] = gain
        assigned |= selected
    rest = solid_mask & ~assigned
    if rest.any():
        day_mean = float(max(lum[rest].mean(), 1e-6))
        gain = float(np.clip(solid_cfg['target_over_scene_mean']['dashboard'] * scene_mean / day_mean, low, high))
        gains['unassigned'] = {'pixels': int(rest.sum()), 'day_mean_luminance': day_mean, 'gain': gain}
        gain_map[rest] = gain
    solid = solid * gain_map[..., None]
    y = luminance(solid)[..., None]
    solid = solid * np.float32(1.0 - solid_cfg['desaturate']) + y * np.float32(solid_cfg['desaturate'])
    white = np.asarray(scene_stats['white_balance_gain'], np.float32)
    solid = solid * (1.0 + np.float32(solid_cfg['white_balance_blend']) * (white - 1.0))
    hood = role_masks.get('hood')
    reflect = (np.clip(hood, 0, 1) if hood is not None else np.zeros(solid_mask.shape, np.float32)) * layers['solid_mask_blend']
    adapted = {**layers, 'solid_rgb': disp(solid),
               'dc_observation_rgb': np.clip(layers['dc_observation_rgb'] * np.float32(profile['observation']['gain']), 0, 1),
               'hood_reflect_mask': reflect.astype(np.float32)}
    parameters = {'adaptation': profile['adaptation'], 'solid': solid_cfg, 'observation': profile['observation'],
                  'hood_reflection': profile['hood_reflection'], 'bloom': profile['bloom']}
    metadata = {'profile_id': profile['profile_id'], 'adaptation': profile['adaptation'],
                'scene_stats': scene_stats, 'solid_gains': gains, 'parameters': parameters}
    return adapted, metadata


def frame_noise(shape: tuple[int, ...], sigma: float, seed: int, frame_index: int) -> np.ndarray:
    if sigma <= 0:
        return np.zeros(shape, np.float32)
    return np.random.default_rng([int(seed), int(frame_index)]).normal(0.0, sigma, shape).astype(np.float32)


def night_frame(clean: np.ndarray, frame_index: int, layers: dict[str, np.ndarray], parameters: dict[str, Any]) -> np.ndarray:
    from scipy.ndimage import gaussian_filter
    clean_lin = lin(clean)
    reflection = parameters['hood_reflection']
    solid_lin = lin(layers['solid_rgb'])
    if reflection['reflectance'] > 0:
        flipped = np.flipud(clean_lin)
        blurred = np.stack([gaussian_filter(flipped[..., k], reflection['blur_sigma_px']) for k in range(3)], axis=-1)
        solid_lin = solid_lin + np.float32(reflection['reflectance']) * blurred * layers['hood_reflect_mask'][..., None]
    solid = disp(solid_lin)
    noise = frame_noise(solid.shape, parameters['solid']['noise_sigma_display'], parameters['solid']['noise_seed'], frame_index)
    solid = np.clip(solid + noise * layers['solid_mask_hard'].astype(np.float32)[..., None], 0.0, 1.0)
    composed = compose_hybrid(clean, layers['dc_alpha'], layers['dc_observation_rgb'], layers['solid_mask_blend'], solid)
    bloom = parameters['bloom']
    if bloom['gain'] > 0:
        scene_lum = luminance(clean_lin)
        bright = np.clip(scene_lum - np.float32(bloom['threshold_linear']), 0, None)
        glow = gaussian_filter(bright, bloom['blur_sigma_px']) * np.float32(bloom['gain'])
        tint = clean_lin / np.maximum(scene_lum, 1e-3)[..., None]
        composed = disp(lin(composed) + glow[..., None] * tint)
    return composed.astype(np.float32)