acra-backend / code /pipeline /cvd_simulation.py
Zeref8425's picture
fix(pipeline): deploy processing refinements from 8ae183d
8cbfe96
Raw History Blame Contribute Delete
14.1 kB
"""
cvd_simulation.py
-----------------
Physiologically accurate Color Vision Deficiency (CVD) simulation based on
the state-of-the-art implementations in DaltonLens:
https://github.com/DaltonLens/DaltonLens-Python
https://daltonlens.org/understanding-cvd-simulation/
Models Implemented:
1. Machado, Oliveira & Fernandes (2009) - PHYSIOLOGICAL MODEL (DEFAULT)
A physiologically-based model for simulation of color vision deficiency.
Simulates anomalous trichromacy and dichromacy by shifting the peak
responsiveness wavelength of cone photoreceptors in LMS space, adapted
to sRGB displays. Full dichromacy (severity 1.0) matches Brettel 1997
scaling while intermediate severities provide continuous, biologically
grounded cone shifts.
2. Brettel, ViΓ©not & Mollon (1997) - TWO-HALF-PLANE LMS PROJECTION
Divides the LMS color space into two half-planes anchored at 475 nm and 575 nm,
meeting along the neutral (white) axis.
3. ViΓ©not, Brettel & Mollon (1999) - SINGLE-MATRIX FAST PATH
Exact single-projection-plane simplification adapted to modern sRGB displays
using Smith & Pokorny (1975) fundamentals.
Fundamentals:
Smith & Pokorny (1975) cone fundamentals adapted to sRGB/Rec.709 displays
with strict white point preservation ([1, 1, 1] -> [1, 1, 1]).
"""
import numpy as np
from typing import Optional, Union
# ── Smith & Pokorny (1975) LMS Color Model adapted to sRGB (BT.709) ─────────
# Recommended by DaltonLens for CVD simulation on standard digital displays.
LMS_FROM_LINEAR_RGB = np.array([
[0.17885956, 0.43997117, 0.03596577],
[0.03380394, 0.27515242, 0.03620635],
[0.00031087, 0.00191661, 0.01528089],
], dtype=np.float64)
LINEAR_RGB_FROM_LMS = np.array([
[ 8.00532950, -12.88195628, 11.68065329],
[ -0.97821211, 5.26945022, -10.18300682],
[ -0.04016557, -0.39885551, 66.48079320],
], dtype=np.float64)
# ── Brettel et al. (1997) Two-Half-Plane Parameters ──────────────────────────
# Precomputed using DaltonLens with sRGB Smith-Pokorny 1975 fundamentals,
# 475 nm and 575 nm monochromatic anchors, and RGB white point preservation.
BRETTEL_PARAMS = {
"deutan": {
"lms_index": 1, # Projects M cone
# Normal of the separation plane going through the neutral diagonal
"n_sep": np.array([-0.01750837, 0.0, 0.6547965], dtype=np.float64),
# Plane 1 projection row (dot(LMS, n_sep) >= 0)
"h1": np.array([0.46165083, 0.0, 2.44884919], dtype=np.float64),
# Plane 2 projection row (dot(LMS, n_sep) < 0)
"h2": np.array([0.45788735, 0.0, 2.58959961], dtype=np.float64),
},
"protan": {
"lms_index": 0, # Projects L cone
"n_sep": np.array([0.0, 0.01750837, -0.34516271], dtype=np.float64),
"h1": np.array([0.0, 2.18394328, -5.65553865], dtype=np.float64),
"h2": np.array([0.0, 2.16613931, -5.30454850], dtype=np.float64),
},
}
# ── Brettel et al. (1997) Full Dichromacy Linear RGB Matrices ────────────────
# Derived from DaltonLens-Python Simulator_Brettel1997 (sRGB Smith-Pokorny 1975).
# Exactly preserves white point [1, 1, 1] and aligns single-matrix operations
# with the reference output of DaltonLens website.
BRETTEL_MATRICES = {
"deutan": np.array([
[ 0.36604, 0.87647, -0.24251],
[ 0.25933, 0.64147, 0.09920],
[-0.01963, 0.02714, 0.99249],
], dtype=np.float64),
"protan": np.array([
[ 0.14312, 1.18474, -0.32786],
[ 0.10471, 0.85523, 0.04006],
[ 0.00430, -0.00594, 1.00164],
], dtype=np.float64),
}
# ── ViΓ©not et al. (1999) Single-Matrix Projection in Linear RGB ──────────────
# Single-plane simplification from DaltonLens (Simulator_Vienot1999 with SmithPokorny75).
VIENOT_MATRICES = {
"deutan": np.array([
[ 0.29031, 0.70969, 0.00000],
[ 0.29031, 0.70969, 0.00000],
[-0.02197, 0.02197, 1.00000],
], dtype=np.float64),
"protan": np.array([
[ 0.10889, 0.89111, 0.00000],
[ 0.10889, 0.89111, 0.00000],
[ 0.00447, -0.00447, 1.00000],
], dtype=np.float64),
}
# ── Machado, Oliveira & Fernandes (2009) Linear RGB Matrices ──────────────────
# Precomputed matrices from DaltonLens (Simulator_Machado2009) for severities 0.0 to 1.0 (step 0.1).
# Shifts the cone peak response wavelength in LMS space and adapts back to sRGB.
MACHADO_MATRICES = {
"deutan": {
0: np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=np.float64),
1: np.array([[0.866435, 0.177704, -0.044139], [0.049567, 0.939063, 0.011370], [-0.003453, 0.007233, 0.996220]], dtype=np.float64),
2: np.array([[0.760729, 0.319078, -0.079807], [0.090568, 0.889315, 0.020117], [-0.006027, 0.013325, 0.992702]], dtype=np.float64),
3: np.array([[0.675425, 0.433850, -0.109275], [0.125303, 0.847755, 0.026942], [-0.007950, 0.018572, 0.989378]], dtype=np.float64),
4: np.array([[0.605511, 0.528560, -0.134071], [0.155318, 0.812366, 0.032316], [-0.009376, 0.023176, 0.986200]], dtype=np.float64),
5: np.array([[0.547494, 0.607765, -0.155259], [0.181692, 0.781742, 0.036566], [-0.010410, 0.027275, 0.983136]], dtype=np.float64),
6: np.array([[0.498864, 0.674741, -0.173604], [0.205199, 0.754872, 0.039929], [-0.011131, 0.030969, 0.980162]], dtype=np.float64),
7: np.array([[0.457771, 0.731899, -0.189670], [0.226409, 0.731012, 0.042579], [-0.011595, 0.034333, 0.977261]], dtype=np.float64),
8: np.array([[0.422823, 0.781057, -0.203881], [0.245752, 0.709602, 0.044646], [-0.011843, 0.037423, 0.974421]], dtype=np.float64),
9: np.array([[0.392952, 0.823610, -0.216562], [0.263559, 0.690210, 0.046232], [-0.011910, 0.040281, 0.971630]], dtype=np.float64),
10: np.array([[0.367322, 0.860646, -0.227968], [0.280085, 0.672501, 0.047413], [-0.011820, 0.042940, 0.968881]], dtype=np.float64),
},
"protan": {
0: np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=np.float64),
1: np.array([[0.856167, 0.182038, -0.038205], [0.029342, 0.955115, 0.015544], [-0.002880, -0.001563, 1.004443]], dtype=np.float64),
2: np.array([[0.734766, 0.334872, -0.069637], [0.051840, 0.919198, 0.028963], [-0.004928, -0.004209, 1.009137]], dtype=np.float64),
3: np.array([[0.630323, 0.465641, -0.095964], [0.069181, 0.890046, 0.040773], [-0.006308, -0.007724, 1.014032]], dtype=np.float64),
4: np.array([[0.539009, 0.579343, -0.118352], [0.082546, 0.866121, 0.051332], [-0.007136, -0.011959, 1.019095]], dtype=np.float64),
5: np.array([[0.458064, 0.679578, -0.137642], [0.092785, 0.846313, 0.060902], [-0.007494, -0.016807, 1.024301]], dtype=np.float64),
6: np.array([[0.385450, 0.769005, -0.154455], [0.100526, 0.829802, 0.069673], [-0.007442, -0.022190, 1.029632]], dtype=np.float64),
7: np.array([[0.319627, 0.849633, -0.169261], [0.106241, 0.815969, 0.077790], [-0.007025, -0.028051, 1.035076]], dtype=np.float64),
8: np.array([[0.259411, 0.923008, -0.182420], [0.110296, 0.804340, 0.085364], [-0.006276, -0.034346, 1.040622]], dtype=np.float64),
9: np.array([[0.203876, 0.990338, -0.194214], [0.112975, 0.794542, 0.092483], [-0.005222, -0.041043, 1.046265]], dtype=np.float64),
10: np.array([[0.152286, 1.052583, -0.204868], [0.114503, 0.786281, 0.099216], [-0.003882, -0.048116, 1.051998]], dtype=np.float64),
},
}
def _linear_to_srgb(c: np.ndarray) -> np.ndarray:
"""Apply standard sRGB gamma electro-optical transfer function."""
c = np.clip(c, 0.0, 1.0).astype(np.float32)
return np.where(
c <= 0.0031308,
c * 12.92,
1.055 * (c ** (1.0 / 2.4)) - 0.055
).astype(np.float32)
def simulate_cvd_brettel1997(
image_linear: np.ndarray,
severity: float = 1.0,
cvd_type: str = "deutan",
) -> np.ndarray:
"""
Simulate CVD perception using Brettel et al. (1997) two-half-plane projection.
This is the most scientifically accurate dichromacy/anomalous-trichromacy model.
Parameters
----------
image_linear : np.ndarray
Linear RGB image (shape (H, W, 3) or (N, 3)), float32/float64, in [0, 1].
severity : float
CVD severity in [0.0, 1.0]. 0 = normal vision, 1 = complete dichromacy.
cvd_type : str
'deutan' or 'protan'.
Returns
-------
np.ndarray
Simulated linear RGB image with the same shape.
"""
if cvd_type not in BRETTEL_PARAMS:
raise ValueError(f"cvd_type must be 'deutan' or 'protan', got: {cvd_type!r}")
severity = float(np.clip(severity, 0.0, 1.0))
if severity <= 0.0:
return image_linear.copy().astype(np.float32)
orig_shape = image_linear.shape
flat = image_linear.reshape(-1, 3).astype(np.float64)
# 1. Linear RGB -> LMS (Smith-Pokorny 1975)
lms = flat @ LMS_FROM_LINEAR_RGB.T
# 2. Select projection half-plane based on separation normal
params = BRETTEL_PARAMS[cvd_type]
idx = params["lms_index"]
n_sep = params["n_sep"]
h1 = params["h1"]
h2 = params["h2"]
mask_h2 = (lms @ n_sep) < 0.0
lms_sim = lms.copy()
lms_sim[~mask_h2, idx] = lms[~mask_h2] @ h1
lms_sim[mask_h2, idx] = lms[mask_h2] @ h2
# 3. LMS -> Linear RGB
dichromat = lms_sim @ LINEAR_RGB_FROM_LMS.T
# 4. Severity interpolation (anomalous trichromacy)
if severity < 0.99999:
sim_linear = (1.0 - severity) * flat + severity * dichromat
else:
sim_linear = dichromat
return sim_linear.reshape(orig_shape).astype(np.float32)
def simulate_cvd_machado2009(
image_linear: np.ndarray,
severity: float = 1.0,
cvd_type: str = "deutan",
) -> np.ndarray:
"""
Simulate CVD perception using Machado, Oliveira & Fernandes (2009).
Physiologically-based model from DaltonLens with continuous spectral cone shifts.
Parameters
----------
image_linear : np.ndarray
Linear RGB image (shape (H, W, 3) or (N, 3)), float32/float64, in [0, 1].
severity : float
CVD severity in [0.0, 1.0]. 0 = normal vision, 1 = complete dichromacy.
cvd_type : str
'deutan' or 'protan'.
Returns
-------
np.ndarray
Simulated linear RGB image with the same shape.
"""
sim_matrix = get_simulation_matrix(severity, cvd_type, model="machado2009")
orig_shape = image_linear.shape
flat = image_linear.reshape(-1, 3).astype(np.float64)
sim_linear = flat @ sim_matrix.T
return sim_linear.reshape(orig_shape).astype(np.float32)
def simulate_cvd_vienot1999(
image_linear: np.ndarray,
severity: float = 1.0,
cvd_type: str = "deutan",
) -> np.ndarray:
"""
Simulate CVD perception using ViΓ©not et al. (1999) single-plane projection.
Equivalent to applying get_simulation_matrix(severity, cvd_type, model="vienot1999").
"""
sim_matrix = get_simulation_matrix(severity, cvd_type, model="vienot1999")
orig_shape = image_linear.shape
flat = image_linear.reshape(-1, 3).astype(np.float64)
sim_linear = flat @ sim_matrix.T
return sim_linear.reshape(orig_shape).astype(np.float32)
def simulate_cvd(
image_linear: np.ndarray,
severity: float,
cvd_type: str,
method: str = "machado2009",
) -> np.ndarray:
"""
Simulate CVD perception of a linear RGB image and return a display-ready sRGB image.
Parameters
----------
image_linear : np.ndarray
Linear RGB image, shape (H, W, 3), float32, values in [0, 1].
severity : float
CVD severity in [0.0, 1.0]. 0 = normal vision, 1 = full dichromacy.
cvd_type : str
'protan' or 'deutan'.
method : str
'machado2009' (physiologically-based, default), 'brettel1997', or 'vienot1999'.
Returns
-------
np.ndarray
Simulated sRGB image, shape (H, W, 3), float32, values in [0, 1].
"""
if method == "machado2009":
sim_linear = simulate_cvd_machado2009(image_linear, severity, cvd_type)
elif method == "brettel1997":
sim_linear = simulate_cvd_brettel1997(image_linear, severity, cvd_type)
elif method == "vienot1999":
sim_linear = simulate_cvd_vienot1999(image_linear, severity, cvd_type)
else:
raise ValueError(f"Unknown simulation method: {method!r}. Choose 'machado2009', 'brettel1997', or 'vienot1999'.")
sim_linear = np.clip(sim_linear, 0.0, 1.0).astype(np.float32)
return _linear_to_srgb(sim_linear)
def get_simulation_matrix(severity: float, cvd_type: str, model: str = "machado2009") -> np.ndarray:
"""
Return the combined Linear RGB β†’ simulated Linear RGB 3x3 matrix.
Defaults to Machado et al. (2009) model (matching DaltonLens reference output).
"""
if cvd_type not in ("protan", "deutan"):
raise ValueError(f"cvd_type must be 'protan' or 'deutan', got: {cvd_type!r}")
severity = float(np.clip(severity, 0.0, 1.0))
if model == "machado2009":
s_lower = int(np.floor(severity * 10.0))
s_higher = min(s_lower + 1, 10)
m1 = MACHADO_MATRICES[cvd_type][s_lower]
m2 = MACHADO_MATRICES[cvd_type][s_higher]
# severity * 10 - s_lower, NOT severity - s_lower/10. Python divides
# first, so the old form left alpha 10x too small and the blend sat
# on the lower table step. It cancelled at multiples of 0.1, which is
# why the 0.8 default and the 1.0 pin never showed it.
alpha = severity * 10.0 - s_lower
return alpha * m2 + (1.0 - alpha) * m1
elif model == "brettel1997":
m_dichromat = BRETTEL_MATRICES[cvd_type]
return (1.0 - severity) * np.eye(3, dtype=np.float64) + severity * m_dichromat
elif model == "vienot1999":
m_dichromat = VIENOT_MATRICES[cvd_type]
return (1.0 - severity) * np.eye(3, dtype=np.float64) + severity * m_dichromat
else:
raise ValueError(f"Unknown simulation model: {model!r}. Choose 'machado2009', 'brettel1997', or 'vienot1999'.")