Skip to content

Commit dfd29a8

Browse files
authored
Merge pull request #422 from emmertex/upstream-cam/2527-kelvin
Upstream #2527: Kelvin white balance for more raws without colour matrices
2 parents 5ee319f + e66addf commit dfd29a8

9 files changed

Lines changed: 363 additions & 39 deletions

File tree

‎crates/catalog/src/model.rs‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -794,7 +794,7 @@ mod edited_tests {
794794
] {
795795
let mut p = Photo::new(PhotoId(1), Source::Demo { scene: 0 }, name, format, 10, 10, "2026-10-01T00:00:00");
796796
p.kind = MediaKind::Raw;
797-
p.meta.camera = "Pentax K-1".into();
797+
p.meta.camera = "Acme X-1".into();
798798
p.as_shot_wb = Some((5200.0, 4.0));
799799
assert_eq!(p.relative_wb(), relative, "{format}");
800800
assert_eq!(p.fitted_look(), relative, "{format}");
@@ -824,7 +824,12 @@ mod edited_tests {
824824
("Canon Canon EOS 5D Mark III", "CR2", false),
825825
("Canon Canon EOS R6m2", "CR3", false),
826826
("Canon Canon EOS R6 Mark II", "CR3", false),
827-
("Canon Canon EOS R7", "CR3", true),
827+
("Canon Canon EOS R7", "CR3", false),
828+
("Canon Canon EOS 20D", "CR2", true),
829+
("Panasonic DMC-GX85", "RW2", false),
830+
("LEICA CAMERA AG D-LUX 7", "RWL", false),
831+
("RICOH PENTAX K-3 Mark III", "PEF", false),
832+
("SONY DSC-R1", "ARW", true),
828833
("FUJIFILM X-T4", "RAF", false),
829834
("ILCE-7M3", "ARW", false),
830835
("SONY ILCE-7M2", "ARW", false),
@@ -846,11 +851,7 @@ mod edited_tests {
846851
p.as_shot_wb = Some((4986.0, -2.0));
847852
assert_eq!(p.relative_wb(), relative, "{camera} {format}");
848853
assert_eq!(relative_wb_camera(format, camera), relative, "{camera} {format}");
849-
assert_eq!(
850-
p.fitted_look(),
851-
format == "ARW" || format == "NEF" || format == "CR2" || format == "CR3" || format == "RAF",
852-
"{camera} {format}"
853-
);
854+
assert_eq!(p.fitted_look(), ["ARW", "NEF", "CR2", "CR3", "RAF", "RW2", "RWL", "PEF"].contains(&format), "{camera} {format}");
854855
let wb = p.camera_defaults().wb;
855856
assert_eq!((wb.temp, wb.tint), if relative { (6500.0, 0.0) } else { (4986.0, -2.0) }, "{camera} {format}");
856857
assert_eq!(wb.scale, if relative { WbScale::Legacy } else { WbScale::Kelvin }, "{camera} {format}");

‎crates/raw/src/kelvin_presets.rs‎

Lines changed: 148 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@
1313
//! taken in Kelvin order ([`KelvinPresets::from_unordered`]). On the PowerShot G1 X Mark III's nine settings the
1414
//! curve reads the as-shot levels within 5 % of the camera's own `ColorTempAsShot`.
1515
//!
16+
//! Canon CR3s list the same presets in the `ColorData` of the maker note (layout by `ColorDataVersion`, see
17+
//! `vendor::cr3`). Panasonic and Leica RW2s store, in tag `0x0027`, neutral multipliers for named lights (D55 and
18+
//! studio tungsten, which are 5500 K and 3200 K: `vendor::rw2`), and Pentax PEFs a table of presets
19+
//! keyed by temperature in maker note tag `0x0221` (`vendor::pef`); each gives the same
20+
//! curve, the two-point ones through [`KelvinPresets::from_neutral_lights`]. All tag numbers were found with a
21+
//! black-box `exiftool` run; the layouts were read from the bytes of the sample files.
22+
//!
1623
//! The model, in `(ln R/G, ln B/G)` of the multipliers ([`KelvinPresets::temp_tint`]):
1724
//! - The presets (three or more) are joined piecewise linearly, with mired linear along each segment and the end segments
1825
//! extended. On every Sony body measured, mired is nearly linear in arc length along the whole curve (2500 K to
@@ -54,9 +61,72 @@ const MAX_TINT: f64 = 150.0;
5461

5562
/// Models other than Sony's whose white balance is edited in Kelvin through their presets, as (brand, Exif model
5663
/// without the brand), each checked to carry them: the Canon PowerShot G1 X Mark III on a reporter's nine photos, one
57-
/// per white-balance setting (issue #157 of a downstream fork). A camera with measured matrices (`crate::spectral`)
58-
/// is read through those instead.
59-
const MODELS: &[(&str, &str)] = &[("CANON", "PowerShot G1 X Mark III")];
64+
/// per white-balance setting (issue #157 of a downstream fork); the other Canon bodies listed here when every sample
65+
/// file of the model (CR2 or CR3) stored a ColorData version with the presets (upstream #2527). A camera with measured matrices (`crate::spectral`) is read through those instead.
66+
const MODELS: &[(&str, &str)] = &[
67+
("CANON", "PowerShot G1 X Mark III"),
68+
("CANON", "EOS 1000D"),
69+
("CANON", "EOS 1100D"),
70+
("CANON", "EOS 1200D"),
71+
("CANON", "EOS 1300D"),
72+
("CANON", "EOS 2000D"),
73+
("CANON", "EOS 30D"),
74+
("CANON", "EOS 4000D"),
75+
("CANON", "EOS 450D"),
76+
("CANON", "EOS 500D"),
77+
("CANON", "EOS 550D"),
78+
("CANON", "EOS 650D"),
79+
("CANON", "EOS 700D"),
80+
("CANON", "EOS 750D"),
81+
("CANON", "EOS 760D"),
82+
("CANON", "EOS 77D"),
83+
("CANON", "EOS 800D"),
84+
("CANON", "EOS 850D"),
85+
("CANON", "EOS 90D"),
86+
("CANON", "EOS DIGITAL REBEL XS"),
87+
("CANON", "EOS DIGITAL REBEL XSi"),
88+
("CANON", "EOS KISS M"),
89+
("CANON", "EOS Kiss F"),
90+
("CANON", "EOS Kiss X3"),
91+
("CANON", "EOS Kiss X4"),
92+
("CANON", "EOS Kiss X80"),
93+
("CANON", "EOS M100"),
94+
("CANON", "EOS M2"),
95+
("CANON", "EOS M200"),
96+
("CANON", "EOS M5"),
97+
("CANON", "EOS M50"),
98+
("CANON", "EOS M50m2"),
99+
("CANON", "EOS M6"),
100+
("CANON", "EOS M6 Mark II"),
101+
("CANON", "EOS R100"),
102+
("CANON", "EOS R3"),
103+
("CANON", "EOS R50 V"),
104+
("CANON", "EOS R6 Mark III"),
105+
("CANON", "EOS R7"),
106+
("CANON", "EOS REBEL T1i"),
107+
("CANON", "EOS REBEL T2i"),
108+
("CANON", "EOS REBEL T3"),
109+
("CANON", "EOS REBEL T4i"),
110+
("CANON", "EOS REBEL T5"),
111+
("CANON", "EOS REBEL T5i"),
112+
("CANON", "EOS REBEL T7i"),
113+
("CANON", "EOS Rebel T100"),
114+
("CANON", "EOS Rebel T6"),
115+
("CANON", "EOS Rebel T6i"),
116+
("CANON", "EOS Rebel T6s"),
117+
("CANON", "EOS Rebel T7"),
118+
("CANON", "EOS Rebel T7i"),
119+
("CANON", "EOS-1D Mark II N"),
120+
("CANON", "EOS-1D Mark III"),
121+
("CANON", "EOS-1D X"),
122+
("CANON", "EOS-1D X Mark III"),
123+
("CANON", "PowerShot G5 X Mark II"),
124+
("CANON", "PowerShot G7 X Mark II"),
125+
("CANON", "PowerShot G7 X Mark III"),
126+
("CANON", "PowerShot G9 X Mark II"),
127+
("CANON", "PowerShot SX70 HS"),
128+
("CANON", "PowerShot V1"),
129+
];
60130

61131
/// Fujifilm's X-Trans III bodies, whose raws carry the camera's own neutral multipliers for Illuminant A and D65
62132
/// (`vendor::raf`, tag `0xf00c`; see [`KelvinPresets::from_neutral_pair`]): checked on the files of each (X-T20,
@@ -69,12 +139,18 @@ const FUJI_MODELS: &[&str] = &["X-T20", "X-T2", "X-Pro2", "X-E3", "X-H1", "X100F
69139
/// three listed here are the only bodies of the 108 sampled without them.
70140
const WITHOUT_PRESETS: &[&str] = &["DSC-F828", "DSC-R1", "DSLR-A100"];
71141

142+
/// Brands other than Sony whose every body of a format that stores its presets is covered, with the models that do
143+
/// not store them (upstream #2527). Panasonic and Leica: the RW2 white balance table (all of 132 models carry it);
144+
/// Pentax: the PEF Kelvin table. A covered model whose file lacks the presets reads as D65 (about 6500 K) instead of
145+
/// relative, so only formats whose files nearly always carry them are here.
146+
const BRANDS: &[(&str, &[&str])] = &[("PANASONIC", &[]), ("LEICA", &[]), ("PENTAX", &["K-3 Mark III Monochrome"])];
147+
72148
/// How Sony names its raw-shooting bodies, for a model given without its make (a Lightroom catalog's camera).
73149
const SONY_MODEL_PREFIXES: &[&str] = &["DSC-", "DSLR-", "ILCA-", "ILCE-", "ILME-", "NEX-", "SLT-", "UMC-", "ZV-"];
74150

75151
/// Whether a raw of this Exif make and model is edited in Kelvin through its presets: a Sony body other than the
76152
/// three without them ([`WITHOUT_PRESETS`]); without a make, a model named as Sony names its bodies; or one of
77-
/// [`MODELS`]; a Fujifilm X-Trans III body ([`FUJI_MODELS`], Fujifilm make or none); or a body with built-in presets ([`crate::kelvin_builtin`]). A camera with
153+
/// [`MODELS`]; a Fujifilm X-Trans III body ([`FUJI_MODELS`], Fujifilm make or none); a body of one of [`BRANDS`]; or a body with built-in presets ([`crate::kelvin_builtin`]). A camera with
78154
/// colour matrices of its own or measured comes first (see [`crate::spectral::find`]): the catalog and the file's
79155
/// scale ask that before this.
80156
pub fn covers(make: Option<&str>, model: &str) -> bool {
@@ -98,6 +174,25 @@ pub fn covers(make: Option<&str>, model: &str) -> bool {
98174
if fuji {
99175
return true;
100176
}
177+
// the brand is the make, or leads the model (Ricoh's Pentax bodies: make RICOH, model "PENTAX K-3 Mark III")
178+
let bare = |b: &str| {
179+
model
180+
.get(..b.len())
181+
.zip(model.get(b.len()..))
182+
.filter(|(p, rest)| p.eq_ignore_ascii_case(b) && rest.starts_with(' '))
183+
.map(|(_, rest)| rest.trim_start())
184+
};
185+
let branded = BRANDS.iter().any(|(b, skip)| {
186+
let rest = match (brand, bare(b)) {
187+
(Some(x), _) if x.eq_ignore_ascii_case(b) => bare(b).unwrap_or(model),
188+
(_, Some(rest)) => rest,
189+
_ => return false,
190+
};
191+
!skip.iter().any(|s| rest.eq_ignore_ascii_case(s))
192+
});
193+
if branded {
194+
return true;
195+
}
101196
let model = model.strip_prefix("SONY ").or_else(|| model.strip_prefix("Sony ")).unwrap_or(model);
102197
let sony = match make {
103198
Some(m) => m.split_whitespace().next().is_some_and(|b| b.eq_ignore_ascii_case("SONY")),
@@ -128,6 +223,9 @@ pub struct KelvinPresets {
128223
/// ([`Self::from_neutral_pair`]); the points are then the line between them at five temperatures.
129224
#[serde(default)]
130225
pair: Option<[[f32; 3]; 2]>,
226+
/// The two lights' chromaticities (warmer first) when the pair is not A and D65.
227+
#[serde(default)]
228+
lights: Option<[[f64; 2]; 2]>,
131229
}
132230

133231
/// Illuminant A and D65 as chromaticities (CIE).
@@ -158,7 +256,11 @@ impl KelvinPresets {
158256
let (a, b) = (log_point(w[0].1), log_point(w[1].1));
159257
w[0].0 < w[1].0 && b[0] > a[0] && b[1] < a[1]
160258
});
161-
ok.then(|| KelvinPresets { points: points.into_iter().map(|(k, m)| (k, [m[0] / m[1], 1.0, m[2] / m[1]])).collect(), pair: None })
259+
ok.then(|| KelvinPresets {
260+
points: points.into_iter().map(|(k, m)| (k, [m[0] / m[1], 1.0, m[2] / m[1]])).collect(),
261+
pair: None,
262+
lights: None,
263+
})
162264
}
163265

164266
/// A curve from presets in any order, as a camera lists them by name (Canon's Daylight, Shade, Cloudy, …):
@@ -188,24 +290,38 @@ impl KelvinPresets {
188290
/// plus the tint the two lights themselves have (A is on the locus, D65 is about +9.5 off it). No other camera's
189291
/// data is involved. `None` for unusable multipliers or two that make no curve.
190292
pub fn from_neutral_pair(a: [f32; 3], d65: [f32; 3]) -> Option<KelvinPresets> {
293+
Self::from_neutral_lights([A_XY, D65_XY], [a, d65])
294+
}
295+
296+
/// [`Self::from_neutral_pair`] for any two lights of known chromaticity, the warmer first (Panasonic stores
297+
/// its D55 and ISO studio tungsten whites): `None` unless the lights are at least 300 K apart.
298+
pub fn from_neutral_lights(lights: [Xy; 2], m: [[f32; 3]; 2]) -> Option<KelvinPresets> {
299+
let [a, d65] = m;
191300
if !usable(a) || !usable(d65) {
192301
return None;
193302
}
303+
let (ta, td) = (cct::xy_to_temp_tint(lights[0]).0, cct::xy_to_temp_tint(lights[1]).0);
304+
if (ta + 300.0).partial_cmp(&td) != Some(std::cmp::Ordering::Less) {
305+
return None;
306+
}
194307
let (a, d65) = ([a[0] / a[1], 1.0, a[2] / a[1]], [d65[0] / d65[1], 1.0, d65[2] / d65[1]]);
195308
let (pa, pd) = (log_point(a), log_point(d65));
196-
let (ma, md) = (1e6 / cct::xy_to_temp_tint(A_XY).0, 1e6 / cct::xy_to_temp_tint(D65_XY).0);
309+
let (ma, md) = (1e6 / ta, 1e6 / td);
197310
let points = POINT_KELVIN.map(|k| {
198311
let f = (1e6 / k as f64 - ma) / (md - ma);
199312
let q = [pa[0] + f * (pd[0] - pa[0]), pa[1] + f * (pd[1] - pa[1])];
200313
(k, [q[0].exp() as f32, 1.0, q[1].exp() as f32])
201314
});
202315
let mut out = KelvinPresets::new(points)?;
203316
out.pair = Some([a, d65]);
317+
if lights != [A_XY, D65_XY] {
318+
out.lights = Some(lights.map(|l| [l.x, l.y]));
319+
}
204320
Some(out)
205321
}
206322

207323
/// [`Self::temp_tint`] for a neutral pair (see [`Self::from_neutral_pair`]).
208-
fn pair_temp_tint(pair: [[f32; 3]; 2], q: [f64; 2]) -> Option<(f64, f64)> {
324+
fn pair_temp_tint(pair: [[f32; 3]; 2], lights: [Xy; 2], q: [f64; 2]) -> Option<(f64, f64)> {
209325
if !pair.iter().all(|m| usable(*m)) {
210326
return None;
211327
}
@@ -221,7 +337,7 @@ impl KelvinPresets {
221337
let r = [q[0] - pa[0], q[1] - pa[1]];
222338
let along = (r[0] * t[0] + r[1] * t[1]) / len;
223339
let off = r[0] * n[0] + r[1] * n[1];
224-
let ((ta, tint_a), (td, tint_d)) = (cct::xy_to_temp_tint(A_XY), cct::xy_to_temp_tint(D65_XY));
340+
let ((ta, tint_a), (td, tint_d)) = (cct::xy_to_temp_tint(lights[0]), cct::xy_to_temp_tint(lights[1]));
225341
let ((u0, v0), (u1, v1)) = (locus_uv(ta), locus_uv(td));
226342
let tint_per_len = cct::TINT_SCALE * (u1 - u0).hypot(v1 - v0) / len;
227343
let mired = 1e6 / ta + along * (1e6 / td - 1e6 / ta);
@@ -236,7 +352,8 @@ impl KelvinPresets {
236352
}
237353
let q = log_point(wb_multipliers);
238354
if let Some(pair) = self.pair {
239-
let (t, tint) = Self::pair_temp_tint(pair, q)?;
355+
let lights = self.lights.map_or([A_XY, D65_XY], |l| l.map(|p| Xy::new(p[0], p[1])));
356+
let (t, tint) = Self::pair_temp_tint(pair, lights, q)?;
240357
return Some((t, tint.clamp(-MAX_TINT, MAX_TINT)));
241358
}
242359
let last = self.points.len().saturating_sub(2);
@@ -304,6 +421,21 @@ mod tests {
304421
.unwrap()
305422
}
306423

424+
#[test]
425+
fn neutral_lights_read_back_and_reject_close_lights() {
426+
let (warm, cool) = (cct::temp_tint_to_xy(3200.0, 0.0), cct::temp_tint_to_xy(5500.0, 0.0));
427+
let (a, d) = ([1.0, 1.0, 2.4], [1.4, 1.0, 1.7]);
428+
let p = KelvinPresets::from_neutral_lights([warm, cool], [a, d]).unwrap();
429+
assert!((p.temp_tint(a).unwrap().0 - 3200.0).abs() < 40.0);
430+
assert!((p.temp_tint(d).unwrap().0 - 5500.0).abs() < 40.0);
431+
assert!(p.temp_tint(a).unwrap().0 < p.temp_tint([1.2, 1.0, 2.0]).unwrap().0);
432+
// lights less than 300 K apart, or in the wrong order, make no line
433+
assert_eq!(KelvinPresets::from_neutral_lights([cool, warm], [d, a]), None);
434+
assert_eq!(KelvinPresets::from_neutral_lights([warm, cct::temp_tint_to_xy(3400.0, 0.0)], [a, d]), None);
435+
// A and D65 as the lights are the plain pair
436+
assert_eq!(KelvinPresets::from_neutral_lights([A_XY, D65_XY], [a, d]), KelvinPresets::from_neutral_pair(a, d));
437+
}
438+
307439
#[test]
308440
fn a_preset_reads_as_its_own_temperature_with_no_tint() {
309441
let p = a99m2();
@@ -387,12 +519,12 @@ mod tests {
387519
assert_eq!(KelvinPresets::from_unordered([(5000.0, g(1400.0, 1400.0)), (6000.0, g(1500.0, 1300.0))]), None);
388520
assert_eq!(KelvinPresets::from_unordered(std::iter::empty()), None);
389521
// a stored curve with a repeated point (only deserializing can make one) reads without dividing by zero
390-
let bad = KelvinPresets { points: vec![(5000.0, g(1400.0, 1400.0)); 3], pair: None };
522+
let bad = KelvinPresets { points: vec![(5000.0, g(1400.0, 1400.0)); 3], pair: None, lights: None };
391523
assert_eq!(bad.temp_tint(g(1400.0, 1400.0)), None);
392-
assert_eq!(KelvinPresets { points: vec![], pair: None }.temp_tint(g(1400.0, 1400.0)), None);
524+
assert_eq!(KelvinPresets { points: vec![], pair: None, lights: None }.temp_tint(g(1400.0, 1400.0)), None);
393525
// a stored pair of one white twice reads without dividing by zero
394526
let w = g(1400.0, 1400.0);
395-
let pair = KelvinPresets { points: vec![], pair: Some([w, w]) };
527+
let pair = KelvinPresets { points: vec![], pair: Some([w, w]), lights: None };
396528
assert_eq!(pair.temp_tint(w), None);
397529
}
398530

@@ -431,7 +563,7 @@ mod tests {
431563
for c in ["FUJIFILM X-T20", "Fujifilm X-T2", "FUJIFILM X100F", "FUJIFILM X-H1", "FUJIFILM X-Pro2", "FUJIFILM X-E3"] {
432564
assert!(covers_camera(c), "{c}");
433565
}
434-
for c in ["FUJIFILM X-T3", "FUJIFILM X-T30", "FUJIFILM GFX 100"] {
566+
for c in ["FUJIFILM X-T3", "FUJIFILM X-T30", "Canon X-T20", "FUJIFILM GFX 100"] {
435567
assert!(!covers_camera(c), "{c}");
436568
}
437569
}
@@ -440,8 +572,9 @@ mod tests {
440572
fn covered_models() {
441573
assert!(covers_camera("NIKON CORPORATION NIKON Z5_2") && covers_camera("NIKON Z5_2") && !covers_camera("NIKON CORPORATION NIKON Z6"));
442574
let covered = ["SONY ILCA-99M2", "SONY DSC-RX10", "SONY ILCE-1M2", "SONY ILCE-1", "SONY DSLR-A200", "SONY ZV-E10M2", "SONY ILME-FX3A"];
443-
let canon = ["Canon Canon PowerShot G1 X Mark III", "Canon PowerShot G1 X Mark III"];
444-
for c in covered.into_iter().chain(canon).chain(["ILCA-99M2", "Sony ilca-99m2", "ILCE-9M3", "SONY SONY ILCE-6700"]) {
575+
let canon = ["Canon Canon PowerShot G1 X Mark III", "Canon PowerShot G1 X Mark III", "Canon EOS R7", "Canon EOS DIGITAL REBEL XSi"];
576+
let brands = ["Panasonic DC-G9M2", "LEICA CAMERA AG D-LUX 7", "RICOH PENTAX K-1 Mark II", "PENTAX K-7"];
577+
for c in covered.into_iter().chain(canon).chain(brands).chain(["ILCA-99M2", "Sony ilca-99m2", "ILCE-9M3", "SONY SONY ILCE-6700"]) {
445578
assert!(covers_camera(c), "{c}");
446579
}
447580
// the three bodies without presets, other makes, a bare make, a make-less model of another maker

0 commit comments

Comments
 (0)