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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
//! Calibration LUT generation from measurements.
//!
//! This module provides tools for generating calibration LUTs from color measurements.
use crate::camera::ColorChecker;
use crate::error::{CalibrationError, CalibrationResult};
use crate::{Matrix3x3, Rgb};
use oximedia_lut::{Lut1d, Lut3d, LutSize};
/// LUT generator for calibration.
pub struct LutGenerator;
impl LutGenerator {
/// Generate a 1D LUT from gamma measurements.
///
/// # Arguments
///
/// * `gamma` - Target gamma value
/// * `size` - LUT size (number of entries)
///
/// # Errors
///
/// Returns an error if generation fails.
pub fn gamma_lut(gamma: f64, size: usize) -> CalibrationResult<Lut1d> {
if size == 0 {
return Err(CalibrationError::LutGenerationFailed(
"LUT size must be greater than 0".to_string(),
));
}
if gamma <= 0.0 {
return Err(CalibrationError::LutGenerationFailed(
"Gamma must be positive".to_string(),
));
}
let mut lut = Lut1d::new(size);
for i in 0..size {
let input = i as f64 / (size - 1) as f64;
let output = input.powf(1.0 / gamma);
lut.set_r(i, output);
lut.set_g(i, output);
lut.set_b(i, output);
}
Ok(lut)
}
/// Generate a 3D calibration LUT from `ColorChecker` measurements.
///
/// Uses inverse-distance-weighted (IDW) interpolation to compute a per-grid-point
/// correction from the measured patches. Each grid point's output is the input
/// plus a weighted average of `(reference_rgb - measured_rgb)` corrections,
/// where the weight for each patch is `1 / (distance² + ε)`.
///
/// If no patches are present, returns an identity LUT (output == input).
///
/// # Arguments
///
/// * `colorchecker` - `ColorChecker` with measured and reference colors
/// * `lut_size` - Size of the 3D LUT
///
/// # Errors
///
/// Returns an error if generation fails.
pub fn from_colorchecker(
colorchecker: &ColorChecker,
lut_size: LutSize,
) -> CalibrationResult<Lut3d> {
// No patches: return an identity LUT so output == input everywhere.
if colorchecker.patches.is_empty() {
return Ok(Lut3d::identity(lut_size));
}
let n = lut_size.as_usize();
let mut lut = Lut3d::new(lut_size);
for ri in 0..n {
for gi in 0..n {
for bi in 0..n {
// Normalize grid indices to [0, 1].
let r = ri as f64 / (n - 1) as f64;
let g = gi as f64 / (n - 1) as f64;
let b = bi as f64 / (n - 1) as f64;
// IDW: accumulate weighted corrections from every patch.
// weight_k = 1 / (dist_k² + ε), correction = ref - measured.
let mut weight_sum = 0.0_f64;
let mut correction = [0.0_f64; 3];
for patch in &colorchecker.patches {
let dr = r - patch.measured_rgb[0];
let dg = g - patch.measured_rgb[1];
let db = b - patch.measured_rgb[2];
let dist_sq = dr * dr + dg * dg + db * db;
let weight = 1.0 / (dist_sq + 1e-10);
correction[0] += weight * (patch.reference_rgb[0] - patch.measured_rgb[0]);
correction[1] += weight * (patch.reference_rgb[1] - patch.measured_rgb[1]);
correction[2] += weight * (patch.reference_rgb[2] - patch.measured_rgb[2]);
weight_sum += weight;
}
// Normalise by total weight and clamp to valid range.
let out_r = (r + correction[0] / weight_sum).clamp(0.0, 1.0);
let out_g = (g + correction[1] / weight_sum).clamp(0.0, 1.0);
let out_b = (b + correction[2] / weight_sum).clamp(0.0, 1.0);
lut.set(ri, gi, bi, [out_r, out_g, out_b]);
}
}
}
Ok(lut)
}
/// Generate a 3D LUT from a color transformation matrix.
///
/// # Arguments
///
/// * `matrix` - 3x3 color transformation matrix
/// * `lut_size` - Size of the 3D LUT
///
/// # Errors
///
/// Returns an error if generation fails.
pub fn from_matrix(matrix: &Matrix3x3, lut_size: LutSize) -> CalibrationResult<Lut3d> {
let size = lut_size.as_usize();
let mut lut = Lut3d::new(lut_size);
for b in 0..size {
for g in 0..size {
for r in 0..size {
let rgb = [
r as f64 / (size - 1) as f64,
g as f64 / (size - 1) as f64,
b as f64 / (size - 1) as f64,
];
let transformed = Self::apply_matrix(matrix, &rgb);
lut.set(r, g, b, transformed);
}
}
}
Ok(lut)
}
/// Apply a 3x3 matrix to an RGB color.
fn apply_matrix(matrix: &Matrix3x3, rgb: &Rgb) -> Rgb {
[
matrix[0][0] * rgb[0] + matrix[0][1] * rgb[1] + matrix[0][2] * rgb[2],
matrix[1][0] * rgb[0] + matrix[1][1] * rgb[1] + matrix[1][2] * rgb[2],
matrix[2][0] * rgb[0] + matrix[2][1] * rgb[1] + matrix[2][2] * rgb[2],
]
}
/// Generate a neutral-axis correction LUT.
///
/// This LUT corrects the neutral (grayscale) axis to ensure pure whites and blacks.
///
/// # Arguments
///
/// * `lut_size` - Size of the 3D LUT
///
/// # Errors
///
/// Returns an error if generation fails.
pub fn neutral_axis_lut(lut_size: LutSize) -> CalibrationResult<Lut3d> {
let size = lut_size.as_usize();
let mut lut = Lut3d::new(lut_size);
for b in 0..size {
for g in 0..size {
for r in 0..size {
let rgb = [
r as f64 / (size - 1) as f64,
g as f64 / (size - 1) as f64,
b as f64 / (size - 1) as f64,
];
// If RGB values are close to each other (neutral), keep them neutral
let avg = (rgb[0] + rgb[1] + rgb[2]) / 3.0;
let max_diff = (rgb[0] - avg)
.abs()
.max((rgb[1] - avg).abs())
.max((rgb[2] - avg).abs());
let corrected = if max_diff < 0.05 {
// Force to neutral
[avg, avg, avg]
} else {
// Keep as-is
rgb
};
lut.set(r, g, b, corrected);
}
}
}
Ok(lut)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gamma_lut() {
let result = LutGenerator::gamma_lut(2.2, 256);
assert!(result.is_ok());
let lut = result.expect("expected successful result");
assert_eq!(lut.size(), 256);
}
#[test]
fn test_gamma_lut_zero_size() {
let result = LutGenerator::gamma_lut(2.2, 0);
assert!(result.is_err());
}
#[test]
fn test_gamma_lut_zero_gamma() {
let result = LutGenerator::gamma_lut(0.0, 256);
assert!(result.is_err());
}
#[test]
fn test_gamma_lut_negative_gamma() {
let result = LutGenerator::gamma_lut(-1.0, 256);
assert!(result.is_err());
}
#[test]
fn test_from_matrix_identity() {
let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
let result = LutGenerator::from_matrix(&identity, LutSize::Size17);
assert!(result.is_ok());
let lut = result.expect("expected successful result");
assert_eq!(lut.size(), LutSize::Size17.as_usize());
}
#[test]
fn test_neutral_axis_lut() {
let result = LutGenerator::neutral_axis_lut(LutSize::Size17);
assert!(result.is_ok());
let lut = result.expect("expected successful result");
assert_eq!(lut.size(), LutSize::Size17.as_usize());
}
#[test]
fn test_apply_matrix() {
let identity = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
let rgb = [0.5, 0.6, 0.7];
let result = LutGenerator::apply_matrix(&identity, &rgb);
assert!((result[0] - 0.5).abs() < 1e-10);
assert!((result[1] - 0.6).abs() < 1e-10);
assert!((result[2] - 0.7).abs() < 1e-10);
}
#[test]
fn test_apply_matrix_scale() {
let scale = [[2.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 2.0]];
let rgb = [0.5, 0.6, 0.7];
let result = LutGenerator::apply_matrix(&scale, &rgb);
assert!((result[0] - 1.0).abs() < 1e-10);
assert!((result[1] - 1.2).abs() < 1e-10);
assert!((result[2] - 1.4).abs() < 1e-10);
}
// ------------------------------------------------------------------
// from_colorchecker tests
// ------------------------------------------------------------------
#[test]
fn test_from_colorchecker_empty_patches() {
use crate::camera::{ColorChecker, ColorCheckerType};
let checker = ColorChecker {
checker_type: ColorCheckerType::Classic24,
patches: vec![],
bounding_box: None,
confidence: 1.0,
};
let result = LutGenerator::from_colorchecker(&checker, LutSize::Size17);
assert!(result.is_ok(), "expected Ok for empty patches");
let lut = result.expect("lut Ok");
// Identity LUT: midpoint of the grid should map to itself.
let mid = 8; // index 8 of 17 → 8/16 = 0.5
let val = lut.get(mid, mid, mid);
assert!(
(val[0] - 0.5).abs() < 1e-6,
"identity R mismatch: {}",
val[0]
);
assert!(
(val[1] - 0.5).abs() < 1e-6,
"identity G mismatch: {}",
val[1]
);
assert!(
(val[2] - 0.5).abs() < 1e-6,
"identity B mismatch: {}",
val[2]
);
}
#[test]
fn test_from_colorchecker_two_patches() {
use crate::camera::{ColorChecker, ColorCheckerType, PatchColor};
let patches = vec![
PatchColor {
index: 0,
measured_rgb: [0.2, 0.2, 0.2],
reference_rgb: [0.25, 0.25, 0.25],
reference_lab: [0.0, 0.0, 0.0],
reference_xyz: [0.0, 0.0, 0.0],
name: "Patch A".to_string(),
},
PatchColor {
index: 1,
measured_rgb: [0.8, 0.8, 0.8],
reference_rgb: [0.75, 0.75, 0.75],
reference_lab: [0.0, 0.0, 0.0],
reference_xyz: [0.0, 0.0, 0.0],
name: "Patch B".to_string(),
},
];
let checker = ColorChecker {
checker_type: ColorCheckerType::Classic24,
patches,
bounding_box: None,
confidence: 1.0,
};
let result = LutGenerator::from_colorchecker(&checker, LutSize::Size17);
assert!(result.is_ok(), "expected Ok with two patches");
let lut = result.expect("lut Ok");
assert_eq!(lut.size(), LutSize::Size17.as_usize());
}
}