Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-color

Source of release 0.8.2

0.8.2 / tools / cameras.py

#!/usr/bin/env python3
"""Write src/camera_data.lucb from the Academy's rawtoaces-data (Apache-2.0,
https://github.com/AcademySoftwareFoundation/rawtoaces-data): measured camera
spectral sensitivities, a prior over them for cameras nobody measured, and the
190 training reflectances.

    cameras.py RAWTOACES_DATA_DIR

- Measured cameras: each one's three curves at 380-780 nm every 5 nm, scaled so
  the highest sample of the three is 1 (their relative gains kept as measured).
- The prior, per channel: the mean of every camera's curve (each scaled to peak
  1) and the first `COMPONENTS` principal components around it. camera.lucb's
  `estimate` fits a camera's curves in it to its raw color matrices.
- Training: the 190 patches rawtoaces fits its matrices on (reflectances)."""
import json, sys
from pathlib import Path
import numpy as np

COMPONENTS = 3
here = Path(__file__).resolve().parent
NM = list(range(380, 781, 5))


def table(path):
    """A dataset's main table, rows by wavelength, as an array (samples × columns)."""
    data = json.load(open(path))
    main = data['spectral_data']['data']['main']
    rows = sorted(main, key=float)
    assert [int(float(k)) for k in rows] == NM, path
    return data['header'], np.array([main[k] for k in rows], float)


def numbers(values, per_line=10):
    text = [f'{v:.5g}' if v != 0 else '0.0' for v in values]
    text = [t if ('.' in t or 'e' in t) else t + '.0' for t in text]
    lines = [', '.join(text[i:i + per_line]) for i in range(0, len(text), per_line)]
    return ',\n    '.join(lines)


def main(folder):
    folder = Path(folder)
    cameras = []
    for path in sorted((folder / 'data' / 'camera').glob('*.json')):
        header, values = table(path)
        assert header.get('license') == 'Apache-2.0', path
        curves = values.T / values.max()
        cameras.append((header['manufacturer'], header['model'], curves))
    cameras.sort(key=lambda c: (c[0].lower(), c[1].lower()))
    _, training = table(folder / 'data' / 'training' / 'training_spectral.json')
    training = training.T
    basis = []
    for channel in range(3):
        shapes = np.array([c[2][channel] / c[2][channel].max() for c in cameras])
        mean = shapes.mean(0)
        _, _, vt = np.linalg.svd(shapes - mean, full_matrices=False)
        basis.append(np.vstack([mean, vt[:COMPONENTS]]))
    out = [
        '## Generated by tools/cameras.py from the Academy\'s rawtoaces-data (Apache-2.0,',
        '## https://github.com/AcademySoftwareFoundation/rawtoaces-data); do not edit.',
        '## camera.lucb reads it.',
        '',
        f'pub let measured_count: usize = {len(cameras)}',
        f'pub let measured_makes: str[{len(cameras)}] = [{", ".join(json.dumps(c[0]) for c in cameras)}]',
        f'pub let measured_models: str[{len(cameras)}] = [{", ".join(json.dumps(c[1]) for c in cameras)}]',
        '## Each camera\'s red, green and blue curves, 81 samples each.',
        f'pub let measured_curves: f64[{len(cameras) * 243}] = [',
        '    ' + numbers([v for c in cameras for v in c[2].ravel()]) + ']',
        '',
        f'pub let basis_size: usize = {COMPONENTS + 1}',
        '## Per channel (red, green, blue): the mean shape, then the components.',
        f'pub let basis: f64[{3 * (COMPONENTS + 1) * 81}] = [',
        '    ' + numbers([v for b in basis for v in b.ravel()]) + ']',
        '',
        f'pub let training_count: usize = {len(training)}',
        f'pub let training: f64[{training.size}] = [',
        '    ' + numbers(training.ravel()) + ']',
        '']
    (here.parent / 'src' / 'camera_data.lucb').write_text('\n'.join(out))
    print(f'wrote src/camera_data.lucb: {len(cameras)} cameras, {len(training)} training reflectances')


if __name__ == '__main__':
    main(sys.argv[1])