File size: 4,999 Bytes
7c2d2fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Quick RGB preview of one Bricker sample (numpy + Pillow only, no model).

    python scripts/visualize.py <sample_dir> [--frame I3] [-o preview.png]

This is a fast *approximate* render: bilinear demosaic -> white balance -> camera-to-sRGB
matrix -> 2.2 gamma.  It deliberately does not use the network-based ISP that produced the
shipped ``rgb_*.png`` files (see ``tools/`` for that).  Use this to get a rough look at the
RAW data, or just open the shipped ``rgb_I1..I5.png`` / ``rgb_gt.png``.
"""

from __future__ import annotations

import argparse
import os

import numpy as np
from PIL import Image

WHITE_LEVEL = 1023.0
GAMMA = 2.2
MU = 5000.0
XYZ2SRGB = np.array(
    [[3.2404542, -1.5371385, -0.4985314],
     [-0.9692660, 1.8760108, 0.0415560],
     [0.0556434, -0.2040259, 1.0572252]],
    dtype=np.float32,
)


def _lossless_gains(as_shot_neutral) -> np.ndarray:
    """Neutral values for the three demosaiced channels (R, G, B)."""
    n = np.asarray(as_shot_neutral, dtype=np.float32).reshape(-1)
    if n.size == 4:  # packed RGGB -> demosaiced RGB (G = mean of G1, G2)
        return np.array([n[0], 0.5 * (n[1] + n[2]), n[3]], dtype=np.float32)
    return n[:3]


def cam_to_srgb(rgb: np.ndarray, color_matrix_1) -> np.ndarray:
    """Camera RGB -> XYZ -> sRGB, matching the pipeline used for the shipped renders."""
    xyz2cam = np.asarray(color_matrix_1, dtype=np.float32).reshape(3, 3)
    xyz2cam = xyz2cam / np.sum(xyz2cam, axis=1, keepdims=True)
    cam2xyz = np.linalg.inv(xyz2cam)
    xyz = np.clip(np.einsum("ij,hwj->hwi", cam2xyz, rgb), 0.0, 1.0)
    m = XYZ2SRGB / np.sum(XYZ2SRGB, axis=1, keepdims=True)
    return np.clip(np.einsum("ij,hwj->hwi", m, xyz), 0.0, 1.0)


def _filter3(img: np.ndarray, kernel: np.ndarray) -> np.ndarray:
    """3x3 'same' convolution with edge padding (numpy only)."""
    p = np.pad(img, 1, mode="edge")
    out = np.zeros_like(img)
    for dy in range(3):
        for dx in range(3):
            out += kernel[dy, dx] * p[dy:dy + img.shape[0], dx:dx + img.shape[1]]
    return out


def unpack_bayer(raw4: np.ndarray) -> np.ndarray:
    """(Hp, Wp, 4) packed RGGB -> (2Hp, 2Wp) single-channel Bayer."""
    h, w, _ = raw4.shape
    bayer = np.zeros((2 * h, 2 * w), dtype=np.float32)
    bayer[0::2, 0::2] = raw4[..., 0]  # R
    bayer[0::2, 1::2] = raw4[..., 1]  # G1
    bayer[1::2, 0::2] = raw4[..., 2]  # G2
    bayer[1::2, 1::2] = raw4[..., 3]  # B
    return bayer


def bilinear_demosaic(bayer: np.ndarray) -> np.ndarray:
    """Classic bilinear demosaic for an RGGB mosaic -> (H, W, 3) RGB."""
    k = np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]], dtype=np.float32) / 4.0
    planes = []
    for dy, dx in ((0, 0), (1, 1)):  # R at (0,0), B at (1,1); green handled below
        mask = np.zeros_like(bayer)
        mask[dy::2, dx::2] = 1.0
        num = _filter3(bayer * mask, k)
        den = _filter3(mask, k)
        planes.append(num / np.maximum(den, 1e-8))
    # green sits on a checkerboard: (0,1) and (1,0)
    gmask = np.zeros_like(bayer)
    gmask[0::2, 1::2] = 1.0
    gmask[1::2, 0::2] = 1.0
    green = _filter3(bayer * gmask, k) / np.maximum(_filter3(gmask, k), 1e-8)
    return np.stack([planes[0], green, planes[1]], axis=-1)


def render(raw4: np.ndarray, meta: dict, curve: str = "mu") -> np.ndarray:
    """(Hp, Wp, 4) uint16/float raw -> uint8 RGB image."""
    raw = raw4.astype(np.float32)
    raw = raw / WHITE_LEVEL if raw4.dtype == np.uint16 else np.clip(raw, 0.0, 1.0)

    rgb = bilinear_demosaic(unpack_bayer(raw))
    rgb = rgb / np.maximum(_lossless_gains(meta["AsShotNeutral"]), 1e-6)
    rgb = cam_to_srgb(np.clip(rgb, 0.0, 4.0), meta["ColorMatrix1"])
    if curve == "mu":
        rgb = np.log1p(MU * np.clip(rgb, 0.0, None)) / np.log1p(MU)
    else:
        rgb = np.power(np.clip(rgb, 0.0, 1.0), 1.0 / GAMMA)
    return (np.clip(rgb, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8)


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("sample_dir")
    ap.add_argument("--frame", default="I3", choices=["I1", "I2", "I3", "I4", "I5", "gt"])
    ap.add_argument("-o", "--out", default=None, help="output PNG (default: preview_<frame>.png next to the sample)")
    ap.add_argument("--curve", default="auto", choices=["auto", "mu", "gamma"],
                    help="display curve: auto = mu for real/, gamma for syn/ (same as the shipped renders)")
    args = ap.parse_args()

    curve = args.curve
    if curve == "auto":
        curve = "gamma" if f"{os.sep}syn{os.sep}" in args.sample_dir or "syn/" in args.sample_dir else "mu"

    meta = np.load(os.path.join(args.sample_dir, "metadata.npy"), allow_pickle=True).item()
    raw = np.load(os.path.join(args.sample_dir, f"raw_{args.frame}.npy"))
    out = args.out or os.path.join(args.sample_dir, f"preview_{args.frame}.png")
    Image.fromarray(render(raw, meta, curve)).save(out)
    print(f"wrote {out}  ({raw.shape[1] * 2} x {raw.shape[0] * 2}, curve={curve})")


if __name__ == "__main__":
    main()