Merge pull request #2966 from OneSlips/pr/upright-posts

LR-EDIT-GEOM-UPRIGHT: Upright corrects posts among people, and says why it found nothing
This commit is contained in:
FredApps authored and GitHub committed 2026-11-26 21:40:32 +01:00
commit 5973d956df
8 files changed
+989 -70

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
//! Upright on real photos (a developer tool, not part of the app): imports each photo of a manifest into an
//! in-memory library, applies its lens settings, runs Upright the way the app does and writes one JSON line per
//! photo (the transform each mode finds and why a mode found nothing). With `--planes DIR` it also saves the
//! analysis plane of each photo at 2048 px (`<key>.lum`: u32 width, u32 height, f32 samples, little endian), so
//! the detector can be tuned on them without decoding raws again (`lightcraft-pipeline` example
//! `upright_planes`).
//!
//! `cargo run --release -p lightcraft-engine --example upright_eval -- <manifest.json> <out.jsonl> [--planes DIR]`
//!
//! The manifest is a JSON array of `{key, local, optics?, orientation?}` (`local`: a copy of the photo; nothing
//! is written next to it). Ground truth and scoring live outside the repository.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::Write;
use lightcraft_engine::Session;
use lightcraft_engine::catalog::PhotoId;
use lightcraft_engine::media::SourceLevel;
use serde_json::{Value, json};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let manifest: Vec<Value> = serde_json::from_str(&std::fs::read_to_string(&args[0]).unwrap()).unwrap();
let mut out = std::fs::File::create(&args[1]).unwrap();
let planes = args.iter().position(|a| a == "--planes").map(|i| std::path::PathBuf::from(&args[i + 1]));
if let Some(p) = &planes {
std::fs::create_dir_all(p).unwrap();
}
for m in &manifest {
// a fresh in-memory library per photo, so a few hundred raws fit
let mut s = Session::new().with_fs();
let key = m["key"].as_str().unwrap().to_string();
let local = m["local"].as_str().unwrap();
let r = match s.execute("library.import", &json!({"paths": [local]})) {
Ok(r) => r,
Err(e) => {
eprintln!("{key}: {e}");
continue;
}
};
let Some(id) = r["imported"][0].as_u64() else {
eprintln!("{key}: not imported");
continue;
};
s.execute("library.select", &json!({"ids": [id], "active": id})).unwrap();
let mut partial = serde_json::Map::new();
for k in ["optics", "orientation"] {
if let Some(v) = m.get(k).filter(|v| !v.is_null()) {
partial.insert(k.into(), v.clone());
}
}
if !partial.is_empty()
&& let Err(e) = s.execute("develop.merge", &json!({"settings": partial}))
{
eprintln!("{key}: lens settings: {e}");
}
let mut line = json!({"key": key});
for mode in ["vertical", "auto", "full", "level"] {
match s.execute("geometry.upright", &json!({"mode": mode})) {
Ok(r) => line[mode] = json!({"transform": r["transform"], "note": r["note"]}),
Err(e) => line[mode] = json!({"error": e.to_string()}),
}
}
if let Some(dir) = &planes {
let d = s.develop_of(PhotoId(id)).unwrap_or_default();
let src = s.source_now(PhotoId(id), SourceLevel::Preview).unwrap();
let info = s.source_info(PhotoId(id));
let lum = lightcraft_pipeline::upright::analysis_luminance(&src, &info, &d, 2048);
let mut bytes = Vec::with_capacity(8 + lum.data.len() * 4);
bytes.extend_from_slice(&(lum.width as u32).to_le_bytes());
bytes.extend_from_slice(&(lum.height as u32).to_le_bytes());
for v in &lum.data {
bytes.extend_from_slice(&v.to_le_bytes());
}
std::fs::write(dir.join(format!("{key}.lum")), bytes).unwrap();
line["source"] = json!([src.width, src.height]);
}
writeln!(out, "{line}").unwrap();
eprintln!("{key} done");
}
}
+20 -5
View File
@@ -1072,19 +1072,22 @@ pub fn specs() -> Vec<CommandSpec> {
"Perspective Correction",
[],
None,
"{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes",
"{mode: off|auto|guided|level|vertical|full} — analyses the photo (line segments → vanishing points) and stores the correction; run again to update after lens changes → {mode, transform, note (why the mode corrects less than it says, and what it did instead, when it does)}",
has_active,
|s, p| {
let mode: Upright =
serde_json::from_value(p.get("mode").cloned().unwrap_or(json!("auto"))).map_err(|e| bad("geometry.upright", e.to_string()))?;
let id = active(s, "geometry.upright")?;
let d = s.develop_of(id).unwrap_or_default();
let transform = match mode {
Upright::Off | Upright::Guided => None,
let (transform, note, family, instead) = match mode {
Upright::Off | Upright::Guided => (None, None, "", None),
m => {
let src = s.source_now(id, SourceLevel::Preview).map_err(|e| bad("geometry.upright", e))?;
let info = s.source_info(id);
Some(lightcraft_pipeline::upright::auto_transform(&src, &info, &d, m))
let a = lightcraft_pipeline::upright::analyze_source(&src, &info, &d);
let family = lightcraft_pipeline::upright::guided_hint(m, &a);
let instead = lightcraft_pipeline::upright::fallback(m, &a);
(Some(lightcraft_pipeline::upright::solve(m, &a)), lightcraft_pipeline::upright::shortfall(m, &a), family, instead)
}
};
edit(s, "geometry.upright", "Perspective Correction", |d| {
@@ -1092,7 +1095,19 @@ pub fn specs() -> Vec<CommandSpec> {
d.geometry.upright_transform = transform;
Ok(())
})?;
Ok(json!({"mode": mode, "transform": transform}))
// say why when the mode can't do what it says, instead of nothing happening
let note = note.map(|why| {
let what = match mode {
Upright::Level => "No level correction",
Upright::Vertical => "No vertical correction",
Upright::Full => "No full correction",
_ => "No perspective correction",
};
// (and what it did instead, when it fell back to a lesser correction: "nothing" is only said of none)
let instead = instead.map(|i| format!(" {i}.")).unwrap_or_default();
format!("{what}: {why}.{instead} Try Guided: draw {family}.")
});
Ok(json!({"mode": mode, "transform": transform, "note": note}))
}
),
cmd!(
+23
View File
@@ -2210,3 +2210,26 @@ fn auto_sync_hdr_enabled_preserves_per_photo_tuning() {
assert!(s.auto_sync, "Auto Sync must remain enabled");
}
}
/// Upright that finds nothing to correct says why instead of silently doing nothing.
#[test]
fn upright_says_why_it_found_nothing_to_correct() {
let mut s = demo();
let mut noted = 0;
for id in s.visible().iter().copied().take(4).collect::<Vec<_>>() {
s.execute("library.select", &json!({"ids": [id.0]})).unwrap();
let r = s.execute("geometry.upright", &json!({"mode": "vertical"})).unwrap();
let identity = r["transform"] == serde_json::to_value(lightcraft_geom::Homography::IDENTITY).unwrap();
match r["note"].as_str() {
Some(note) => {
noted += 1;
assert!(identity || note.contains(" instead."), "a correction was applied but the note doesn't say which: {r}");
assert!(note.starts_with("No vertical correction: "), "{note}");
}
None => assert!(!identity, "a vertical correction was found: {r}"),
}
}
assert!(noted > 0, "the demo's natural scenes have no verticals to correct");
let r = s.execute("geometry.upright", &json!({"mode": "off"})).unwrap();
assert!(r["note"].is_null());
}
@@ -0,0 +1,47 @@
//! Upright detector on saved analysis planes (a developer tool, not part of the app): reads the `.lum` planes
//! that `lightcraft-engine`'s `upright_eval` example saves, runs the line finder and the solver at the app's
//! analysis size and writes one JSON line per plane (the Vertical / Auto / Full transforms and why a mode found
//! nothing), so a change to the detector can be scored against the photographer's own corrections quickly.
//!
//! `cargo run --release -p lightcraft-pipeline --example upright_planes -- <planes dir> <out.jsonl>`
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::io::Write;
use lightcraft_develop::Upright;
use lightcraft_pipeline::upright;
use lightcraft_raster::Plane;
fn read_plane(path: &std::path::Path) -> Plane {
let b = std::fs::read(path).unwrap();
let w = u32::from_le_bytes(b[0..4].try_into().unwrap()) as usize;
let h = u32::from_le_bytes(b[4..8].try_into().unwrap()) as usize;
let data = b[8..].as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect();
Plane { width: w, height: h, data }
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let mut out = std::fs::File::create(&args[1]).unwrap();
let mut paths: Vec<_> = std::fs::read_dir(&args[0]).unwrap().filter_map(|e| e.ok().map(|e| e.path())).collect();
paths.retain(|p| p.extension().is_some_and(|e| e == "lum"));
paths.sort();
for p in paths {
let key = p.file_stem().unwrap().to_string_lossy().to_string();
let plane = read_plane(&p);
let size = std::env::var("UPRIGHT_SIZE").ok().and_then(|v| v.parse::<usize>().ok()).filter(|&n| n > 0).unwrap_or(1024);
let a = upright::analyze_plane_at(&plane, size);
let mut line = serde_json::json!({"key": key});
for (name, mode) in [("vertical", Upright::Vertical), ("auto", Upright::Auto), ("full", Upright::Full)] {
line[name] = serde_json::json!({"transform": upright::solve(mode, &a), "note": upright::shortfall(mode, &a)});
}
writeln!(out, "{line}").unwrap();
// UPRIGHT_DUMP=dir: the near-vertical lines and the vanishing point, to draw over the photo
if let Ok(dir) = std::env::var("UPRIGHT_DUMP") {
let segs: Vec<[f64; 4]> = a.vertical.iter().map(|s| [s.a.x, s.a.y, s.b.x, s.b.y]).collect();
let h: Vec<[f64; 4]> = a.horizontal.iter().map(|s| [s.a.x, s.a.y, s.b.x, s.b.y]).collect();
let d = serde_json::json!({"vertical": segs, "horizontal": h, "vp": a.vertical_vp.or(upright::vanishing_point(&a.vertical).map(|x| x.0)), "why": a.vertical_why.map(|w| w.message())});
std::fs::write(std::path::Path::new(&dir).join(format!("{key}.json")), d.to_string()).unwrap();
}
}
}
+329
View File
@@ -687,3 +687,332 @@ fn the_analysis_cache_tells_lenses_and_optics_apart() {
assert!(!off.section_enabled("optics"));
assert_ne!(key(&src, &plain, &s), key(&src, &plain, &off), "the optics section off");
}
/// A ceremony aisle under a pavilion, shot from below and slightly rolled. Two thick white posts,
/// left and right, clipped by the frame's top and bottom, converge; a level hedge line; in the middle, people and
/// a dress whose edges are near-vertical but point nowhere in common; tree texture behind. Upright Vertical / Auto
/// did nothing on such a photo.
fn pavilion(w: usize, h: usize, fwd: lightcraft_geom::Homography) -> Rgb32f {
let l = w.max(h) as f64 / 2.0;
let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
// cheap deterministic noise
let noise = |x: f64, y: f64| {
let n = ((x * 12.9898 + y * 78.233).sin() * 43758.5453).fract().abs();
n as f32
};
synth(
w,
h,
move |p| {
let q = fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l));
Point::new(q.x, q.y)
},
move |q| {
let (x, y) = (q.x, q.y);
// posts: thick, bright, the whole height
for px in [-0.78, 0.8] {
if (x - px).abs() < 0.045 {
return [0.95; 3];
}
}
// people in the middle: tilted shapes (a dress, suits), near-vertical edges in every direction
let people: [(f64, f64, f64, f64, f32); 6] = [
(-0.32, 0.25, 0.09, 9.0, 0.08),
(-0.12, 0.2, 0.13, -11.0, 0.92),
(0.05, 0.22, 0.08, 14.0, 0.1),
(0.22, 0.28, 0.07, -7.0, 0.85),
(0.38, 0.3, 0.06, 18.0, 0.15),
(-0.5, 0.33, 0.05, -16.0, 0.12),
];
for (px, py, half_w, tilt, v) in people {
let (s, c) = tilt.to_radians().sin_cos();
let (dx, dy) = (x - px, y - py);
let (u, t) = (dx * c - dy * s, dx * s + dy * c);
// a body from py − 0.35 (head) to py + 0.35, wider at the bottom (a dress)
if t.abs() < 0.35 && u.abs() < half_w * (1.0 + 0.8 * (t + 0.35)) {
return [v; 3];
}
}
if y < -0.12 {
// sky (bright, but not as bright as the white posts)
[0.62 - 0.05 * y.abs() as f32; 3]
} else if y < 0.08 {
// trees: dark, textured
[0.18 + 0.12 * noise((x * 90.0).floor(), (y * 90.0).floor()); 3]
} else {
// lawn, below a level hedge line
[0.42 + 0.06 * noise((x * 140.0).floor(), (y * 140.0).floor()); 3]
}
},
)
}
#[test]
fn upright_corrects_converging_posts_among_people() {
let (w, h) = (900usize, 600usize);
let shot = lightcraft_develop::Geometry { vertical: 30.0, rotate: -1.5, ..Default::default() };
let src = pavilion(w, h, crate::transform::manual(&shot));
let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default());
assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why);
// the middle of the bright post in a quarter of the frame, on a row (centroid of the white pixels)
let post_x = |img: &Rgba8, y: usize, right: bool| {
let (a, b) = if right { (img.width * 3 / 4, img.width) } else { (0, img.width / 4) };
let (mut s, mut n) = (0.0f64, 0.0f64);
for x in a..b {
if img.get(x, y)[1] > 225 {
s += x as f64;
n += 1.0;
}
}
assert!(n > 0.0, "a post is visible on row {y}");
s / n
};
let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 6, right) - post_x(img, img.height * 5 / 6, right);
let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image;
assert!(lean(&raw, false).abs() > 8.0 && lean(&raw, true).abs() > 8.0, "the posts lean in the photo: {} {}", lean(&raw, false), lean(&raw, true));
for mode in [Upright::Vertical, Upright::Auto] {
let img = upright_render(&src, mode);
for right in [false, true] {
assert!(
lean(&img, right).abs() < 2.5,
"{mode:?}: the {} post still leans {} px",
if right { "right" } else { "left" },
lean(&img, right)
);
}
}
}
/// A ceremony under a white gazebo, shot level with a long lens but rolled 1.6°
/// (portrait). Two white posts stand up the whole frame; the deck's boards run away to the horizon (they meet
/// inside the photo); two drapes hang diagonally from the roof; a couple stands between the posts. Upright
/// Vertical said "the straight lines point in different directions" and did nothing.
fn gazebo(w: usize, h: usize, fwd: lightcraft_geom::Homography) -> Rgb32f {
let l = w.max(h) as f64 / 2.0;
let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
synth(
w,
h,
move |p| fwd.apply(Point::new((p.x - cx) / l, (p.y - cy) / l)),
move |q| {
let (x, y) = (q.x, q.y);
for px in [-0.47, 0.47] {
if (x - px).abs() < 0.035 {
return [0.95; 3];
}
}
// drapes from the roof's middle out and down, thin bright bands
for (x0, x1) in [(-0.05, -0.3), (0.05, 0.3)] {
let (y0, y1) = (-1.0, 0.25);
if y > y0 && y < y1 {
let t = (y - y0) / (y1 - y0);
if (x - (x0 + (x1 - x0) * t)).abs() < 0.02 {
return [0.7; 3];
}
}
}
// the couple: a dark suit and a white gown, a little tilted
for (px, half_w, tilt, v) in [(-0.1, 0.07, 6.0f64, 0.85f32), (0.1, 0.06, -5.0, 0.08)] {
let (s, c) = tilt.to_radians().sin_cos();
let (dx, dy) = (x - px, y - 0.25);
let (u, t) = (dx * c - dy * s, dx * s + dy * c);
if t.abs() < 0.4 && u.abs() < half_w * (1.0 + 0.8 * (t + 0.4)) {
return [v; 3];
}
}
if y > 0.3 {
// deck boards running to a point on the horizon (inside the photo)
let a = x.atan2(y + 0.1);
if (a * 14.0).rem_euclid(1.0) < 0.12 {
return [0.15; 3];
}
return [0.55; 3];
}
// sky, a railing line
if (y - 0.05).abs() < 0.01 { [0.3; 3] } else { [0.62; 3] }
},
)
}
#[test]
fn upright_vertical_follows_the_posts_not_the_deck_or_the_drapes() {
let (w, h) = (600usize, 900usize);
let shot = lightcraft_develop::Geometry { rotate: 1.6, ..Default::default() };
let src = gazebo(w, h, crate::transform::manual(&shot));
let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default());
assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why);
let post_x = |img: &Rgba8, y: usize, right: bool| {
let (a, b) = if right { (img.width * 3 / 4, img.width) } else { (0, img.width / 4) };
let (mut s, mut n) = (0.0f64, 0.0f64);
for x in a..b {
if img.get(x, y)[1] > 235 {
s += x as f64;
n += 1.0;
}
}
assert!(n > 0.0, "a post is visible on row {y}");
s / n
};
let lean = |img: &Rgba8, right: bool| post_x(img, img.height / 8, right) - post_x(img, img.height * 5 / 8, right);
let raw = render(&src, &SourceInfo::default(), &DevelopSettings::default(), &RenderRequest::fit(w, h)).image;
assert!(lean(&raw, false).abs() > 6.0 && lean(&raw, true).abs() > 6.0, "the posts lean: {} {}", lean(&raw, false), lean(&raw, true));
for mode in [Upright::Vertical, Upright::Auto] {
let img = upright_render(&src, mode);
for right in [false, true] {
assert!(
lean(&img, right).abs() < 2.0,
"{mode:?}: the {} post still leans {} px",
if right { "right" } else { "left" },
lean(&img, right)
);
}
}
}
/// Do no harm: a gown's folds spreading to the floor point at a far point too, but they are short and there is
/// no post, wall or door among them: Upright Vertical leaves such a photo alone.
#[test]
fn upright_vertical_leaves_a_gown_without_structure_alone() {
let (w, h) = (600usize, 900usize);
let l = 450.0;
let src = synth(
w,
h,
|p| Point::new((p.x - 300.0) / l, (p.y - 450.0) / l),
|q| {
let (x, y) = (q.x, q.y);
// the gown: from the waist (y = −0.1) to the floor (y = 0.9), widening
if y > -0.1 && y < 0.9 && x.abs() < 0.08 + 0.45 * (y + 0.1) {
// folds: soft, wavy dark lines that all aim at a point far below (y = 3)
let a = x.atan2(3.0 - y) + 0.012 * (y * 23.0).sin();
let band = (a * 40.0).rem_euclid(1.0) < 0.15;
let piece = ((y * 9.0).floor() as i64 + (a * 40.0).floor() as i64).rem_euclid(3) == 0;
return if band && piece { [0.55; 3] } else { [0.92; 3] };
}
// a plain, soft background
[0.35 + 0.05 * (x as f32); 3]
},
);
let a = crate::upright::analyze_source(&src, &SourceInfo::default(), &DevelopSettings::default());
assert!(a.vertical_vp.is_none(), "folds are not structure: {:?}", a.vertical_vp);
assert!(crate::upright::shortfall(Upright::Vertical, &a).is_some(), "and it says why");
}
/// Auto's note follows what Auto did: a tilted horizon it won't fix (over 5°) and a vertical correction too steep
/// to make both say why, while a level horizon it accepts says nothing.
#[test]
fn upright_auto_says_why_whenever_it_leaves_the_photo_alone() {
use crate::upright::{Analysis, Reject, Segment, shortfall, solve};
use lightcraft_develop::Upright;
use lightcraft_geom::Homography;
let line = |deg: f64, y: f64| {
let (s, c) = deg.to_radians().sin_cos();
Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) }
};
// a level horizon: Auto accepts a zero-degree correction, so it has nothing to explain
let level = Analysis { horizontal: vec![line(0.0, -0.2), line(0.0, 0.2)], ..Analysis::default() };
assert_eq!(shortfall(Upright::Auto, &level), None);
// a horizon 10° off: Auto leaves it alone, and says so
let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() };
assert_eq!(solve(Upright::Auto, &tilted), Homography::IDENTITY);
assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooTilted.message()), "too tilted, not too few lines");
assert_ne!(solve(Upright::Level, &tilted), Homography::IDENTITY, "Level still fixes it");
// lines meeting just below the photo: too steep for Auto, which says so; Vertical still corrects them
let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() };
assert_eq!(solve(Upright::Auto, &steep), Homography::IDENTITY);
assert_eq!(shortfall(Upright::Auto, &steep), Some(Reject::TooSteep.message()));
assert_ne!(solve(Upright::Vertical, &steep), Homography::IDENTITY);
// Level with no lines at all says there are too few, not that they disagree
assert_eq!(shortfall(Upright::Level, &Analysis::default()), Some(Reject::TooFew.message()));
}
/// A mode that falls back to a lesser correction says which one it applied, and "no correction" is kept for no
/// correction at all (CodeRabbit on #2966).
#[test]
fn upright_note_names_the_fallback_it_applied() {
use crate::upright::{Analysis, Segment, fallback, shortfall, solve};
use lightcraft_develop::Upright;
use lightcraft_geom::Homography;
let line = |deg: f64, y: f64| {
let (s, c) = deg.to_radians().sin_cos();
Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) }
};
// no verticals, a tilted horizon: Vertical and Full both level it, and say so
let tilted = Analysis { horizontal: vec![line(4.0, -0.2), line(4.0, 0.2)], ..Analysis::default() };
for m in [Upright::Vertical, Upright::Full] {
assert!(shortfall(m, &tilted).is_some());
assert_ne!(solve(m, &tilted), Homography::IDENTITY);
assert_eq!(fallback(m, &tilted), Some("Levelled the photo instead"), "{m:?}");
}
// a vertical vanishing point but no horizontal one: Full straightens the verticals
let vertical = Analysis { vertical_vp: Some([0.0, 3.0, 1.0]), ..Analysis::default() };
assert!(shortfall(Upright::Full, &vertical).is_some());
assert_ne!(solve(Upright::Full, &vertical), Homography::IDENTITY);
assert_eq!(fallback(Upright::Full, &vertical), Some("Straightened the vertical lines instead"));
assert_eq!(fallback(Upright::Vertical, &vertical), None, "Vertical did what it says");
// verticals already along the image's y axis: Full stores no correction, so it names no fallback
let straight = Analysis { vertical_vp: Some([0.0, 1.0, 0.0]), ..Analysis::default() };
assert!(shortfall(Upright::Full, &straight).is_some());
assert_eq!(solve(Upright::Full, &straight), Homography::IDENTITY);
assert_eq!(fallback(Upright::Full, &straight), None);
// nothing at all to go by: no fallback, the note says there was no correction
for m in [Upright::Vertical, Upright::Full, Upright::Level] {
assert_eq!(fallback(m, &Analysis::default()), None);
assert_eq!(solve(m, &Analysis::default()), Homography::IDENTITY);
}
}
/// The Guided hint says what to draw: Full needs two guides of each family (Guided uses only the guides drawn, and
/// one of a kind only levels), Vertical two vertical ones, and Level a single line.
#[test]
fn upright_hint_asks_for_the_lines_guided_needs() {
use crate::upright::{Analysis, Segment, guided_hint};
use lightcraft_develop::Upright;
let none = Analysis::default();
assert_eq!(guided_hint(Upright::Full, &none), "two lines along what should be vertical and two along what should be horizontal");
assert_eq!(guided_hint(Upright::Vertical, &none), "two lines along what should be vertical");
assert_eq!(guided_hint(Upright::Level, &none), "a line along what should be level or upright");
// Auto with no usable lines: either kind of guide can help
assert_eq!(guided_hint(Upright::Auto, &none), "two lines along what should be vertical, or one line along what should be level");
// Auto stopped by a horizon over 5°: one level line fixes it (solve_guided_levels_one_guide_of_each_family_only)
let line = |deg: f64, y: f64| {
let (s, c) = deg.to_radians().sin_cos();
Segment { a: Point::new(-0.4 * c, y - 0.4 * s), b: Point::new(0.4 * c, y + 0.4 * s) }
};
let tilted = Analysis { horizontal: vec![line(10.0, -0.2), line(10.0, 0.2)], ..Analysis::default() };
assert_eq!(guided_hint(Upright::Auto, &tilted), "one line along what should be level");
// the same tilt found from vertical lines only (posts 10° off, no horizon): one upright line, as
// one vertical guide levels too (CodeRabbit, #2966)
let leaning = Analysis { vertical: vec![line(100.0, -0.2), line(100.0, 0.2)], ..Analysis::default() };
assert_eq!(guided_hint(Upright::Auto, &leaning), "one line along what should be upright");
// Auto stopped by converging posts too steep for it: a level line can't straighten them (CodeRabbit, #2966)
let steep = Analysis { vertical_vp: Some([0.0, 0.3, 1.0]), ..Analysis::default() };
assert_eq!(guided_hint(Upright::Auto, &steep), "two lines along what should be vertical");
}
/// What the hints promise is what Guided does: one vertical and one horizontal guide only level (the horizontal one
/// becomes level, the vertical one keeps its lean, so Full's hint asks for two of each), and the single level line
/// Auto's hint offers fixes the horizon Auto leaves alone for being more than 5° off.
#[test]
fn solve_guided_levels_one_guide_of_each_family_only() {
use crate::upright::{Analysis, Reject, Segment, shortfall, solve_guided};
use lightcraft_develop::Upright;
let vertical = Segment { a: Point::new(0.1, -0.5), b: Point::new(0.19, 0.5) };
let horizontal = Segment { a: Point::new(-0.5, 0.1), b: Point::new(0.5, 0.12) };
let h = solve_guided(&[vertical, horizontal]);
let (p, q) = (h.apply(horizontal.a), h.apply(horizontal.b));
assert!((p.y - q.y).abs() < 1e-9, "the horizontal guide is levelled: {p:?} {q:?}");
let (p, q) = (h.apply(vertical.a), h.apply(vertical.b));
assert!((p.x - q.x).abs() > 0.03, "the vertical guide keeps its lean (no full correction): {p:?} {q:?}");
// a horizon 10° off: too tilted for Auto, levelled by the one line its hint asks for
let (s, c) = 10f64.to_radians().sin_cos();
let horizon = Segment { a: Point::new(-0.4 * c, -0.4 * s), b: Point::new(0.4 * c, 0.4 * s) };
let tilted = Analysis {
horizontal: vec![horizon, Segment { a: Point::new(horizon.a.x, 0.2 + horizon.a.y), b: Point::new(horizon.b.x, 0.2 + horizon.b.y) }],
..Analysis::default()
};
assert_eq!(shortfall(Upright::Auto, &tilted), Some(Reject::TooTilted.message()));
let h = solve_guided(&[horizon]);
let (p, q) = (h.apply(horizon.a), h.apply(horizon.b));
assert!((p.y - q.y).abs() < 1e-9, "one level guide fixes it: {p:?} {q:?}");
}
+473 -59
View File
@@ -99,7 +99,8 @@ pub fn detect_segments(lum: &Plane) -> Vec<Segment> {
}
sorted.sort_by(f32::total_cmp);
let p90 = sorted[sorted.len() * 9 / 10];
let thr = (p90 * 0.35).max(0.008);
// a quarter of the 90th percentile: a post's edge against foliage stays in
let thr = (p90 * 0.25).max(0.008);
let mut order: Vec<u32> = (0..n as u32).filter(|&i| mag[i as usize] > thr).collect();
order.sort_by(|&a, &b| mag[b as usize].total_cmp(&mag[a as usize]));
let mut used = vec![false; n];
@@ -273,6 +274,11 @@ fn refine_vp(segs: &[&Segment]) -> [f64; 3] {
/// The dominant vanishing point of a segment family: RANSAC over pairs, then least squares on the inliers.
/// Returns the point and the total inlier length, or None with fewer than two consistent segments.
pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> {
vanishing_point_where(segs, |_| true)
}
/// [`vanishing_point`] among the candidate points `ok` accepts.
fn vanishing_point_where(segs: &[Segment], ok: impl Fn([f64; 3]) -> bool) -> Option<([f64; 3], f64)> {
if segs.len() < 2 {
return None;
}
@@ -290,6 +296,9 @@ pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> {
continue;
}
let v = norm(v);
if !ok(v) {
continue;
}
let sc = score(v);
if best.is_none_or(|b| sc > b.1) {
best = Some((v, sc));
@@ -301,7 +310,8 @@ pub fn vanishing_point(segs: &[Segment]) -> Option<([f64; 3], f64)> {
if inl.len() < 2 {
return None;
}
let v = refine_vp(&inl);
// refined, the point must still be one `ok` accepts (else the candidate it came from stands)
let v = Some(refine_vp(&inl)).filter(|r| ok(*r)).unwrap_or(v);
let total: f64 = segs.iter().filter(|s| vp_error(s, v) < thr * 2.0).map(|s| s.len()).sum();
let count = segs.iter().filter(|s| vp_error(s, v) < thr * 2.0).count();
(count >= 2).then_some((v, total))
@@ -380,6 +390,14 @@ fn level_angle(vert: &[Segment], horiz: &[Segment]) -> Option<f64> {
/// [`level_angle`] that only answers for at most `max` degrees, backed by at least `min_lines`
/// agreeing segments.
/// Whether levelling goes by the vertical lines: the horizontal ones lead unless there are none or
/// their length is under half the verticals'.
fn levels_by_vertical(vert: &[Segment], horiz: &[Segment]) -> bool {
let lh: f64 = horiz.iter().map(Segment::len).sum();
let lv: f64 = vert.iter().map(Segment::len).sum();
!(lh >= lv * 0.5 && lh > 0.0)
}
pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64, min_lines: usize) -> Option<f64> {
let dev = |s: &Segment, vertical: bool| {
let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y);
@@ -395,9 +413,8 @@ pub(crate) fn level_angle_within(vert: &[Segment], horiz: &[Segment], max: f64,
};
if vertical { -a } else { a }
};
let lh: f64 = horiz.iter().map(Segment::len).sum();
let lv: f64 = vert.iter().map(Segment::len).sum();
let (set, vertical) = if lh >= lv * 0.5 && lh > 0.0 { (horiz, false) } else { (vert, true) };
let vertical = levels_by_vertical(vert, horiz);
let set = if vertical { vert } else { horiz };
if set.is_empty() {
return None;
}
@@ -429,36 +446,313 @@ pub struct Analysis {
pub horizontal: Vec<Segment>,
pub vertical_vp: Option<[f64; 3]>,
pub horizontal_vp: Option<[f64; 3]>,
/// Why there is no vertical vanishing point (when there is none).
pub vertical_why: Option<Reject>,
/// Why there is no horizontal vanishing point (when there is none).
pub horizontal_why: Option<Reject>,
}
/// Why a family of lines gives no perspective to correct.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reject {
/// Fewer than two long lines of the family.
TooFew,
/// Too little of them: short lines only.
TooShort,
/// All on one object: not spread across the photo.
OneObject,
/// They point in different directions (trees, people, folds), not at one vanishing point.
Disagree,
/// They meet inside or near the photo: a scene feature (a road, rays), not a tilted camera.
MeetInside,
/// Correcting them would turn the camera too far to be a tilt (Auto leaves it to Vertical).
TooSteep,
/// The lines it would level by (horizontal, else vertical) are tilted more than Auto levels (5°): usually
/// intentional, or scene lines (Level fixes it anyway).
TooTilted,
}
impl Reject {
/// In words for the user: "No vertical correction: …".
pub fn message(self) -> &'static str {
match self {
Reject::TooFew => "too few straight lines",
Reject::TooShort => "the straight lines are too short",
Reject::OneObject => "the straight lines are all on one object",
Reject::Disagree => "the long lines lean different ways",
Reject::MeetInside => "the lines meet inside the photo (a floor or a road, not a tilted camera)",
Reject::TooSteep => "the lines lean too far to be a tilted camera (Vertical corrects them anyway)",
Reject::TooTilted => "the lines are tilted too far to be a levelling fix (Level corrects them anyway)",
}
}
}
/// How far (degrees) the camera turns to send the vertical vanishing point `v` to the image's y axis.
fn tilt_degrees(v: [f64; 3]) -> f64 {
let d = direction(v, DEFAULT_FOCAL);
d[1].abs().clamp(0.0, 1.0).acos().to_degrees()
}
/// Whether a (homogeneous) vanishing point lies inside or near the photo (within twice the half long edge of
/// its centre): a scene feature rather than a camera tilt.
fn inside(v: [f64; 3]) -> bool {
v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0
}
/// A long line (in half long edges: 7.5 % of the long edge), and how far apart (across the family) two of them
/// must be to vouch for a vanishing point. Tuned on a photographer's own Upright corrections.
const LONG_LINE: f64 = 0.15;
const LONG_APART: f64 = 0.25;
/// Camera turns (degrees) above which a vertical correction needs three long lines and half the long lines'
/// length agreeing, and above which it needs most of it.
const BIG_TILT: f64 = 10.0;
const HUGE_TILT: f64 = 20.0;
/// Whether a family's vanishing point is backed by real structure rather than one object: at least three
/// inlier segments, a total inlier length of a quarter of the long edge, and inliers spread across at least a
/// fifth of the long edge perpendicular to the family, and at least 60 % of the family's length agreeing (the
/// mirrored flanks of conical trees or peaks converge somewhere but say nothing about the camera).
fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> bool {
/// fifth of the long edge perpendicular to the family, and most of the family's long lines agreeing (the
/// mirrored flanks of conical trees or peaks converge somewhere but say nothing about the camera), or at least
/// the lines that disagree not gathering at a rival point (two posts flanking a crowd).
fn reliable(segs: &[Segment], v: [f64; 3], vertical: bool) -> Result<(), Reject> {
let thr = 3f64.to_radians();
let inl: Vec<&Segment> = segs.iter().filter(|s| vp_error(s, v) < thr).collect();
let total: f64 = inl.iter().map(|s| s.len()).sum();
let across = |s: &&Segment| if vertical { s.mid().x } else { s.mid().y };
let (lo, hi) = inl.iter().map(across).fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(x), hi.max(x)));
// consensus: real structure agrees; mirrored flanks (trees, peaks) split the family roughly in half
let family: f64 = segs.iter().map(Segment::len).sum();
// a camera-tilt vanishing point lies far outside the frame; one inside or near it is a scene feature
// (sun rays, a road to the horizon), not perspective to correct
if v[2].abs() > 1e-9 && (v[0] / v[2]).hypot(v[1] / v[2]) < 2.0 {
if inside(v) {
return Err(Reject::MeetInside);
}
if inl.len() < 3 {
return Err(Reject::TooFew);
}
if total < 0.5 {
return Err(Reject::TooShort);
}
if hi - lo < 0.4 {
return Err(Reject::OneObject);
}
// real structure has long straight edges: at least two long lines, apart, agree (folds of a dress, hair
// and foliage are short pieces that agree by chance)
let long: Vec<f64> = inl.iter().filter(|s| s.len() >= LONG_LINE).map(across).collect();
let spread = long.iter().fold((f64::MAX, f64::MIN), |(lo, hi), x| (lo.min(*x), hi.max(*x)));
if long.len() < 2 || spread.1 - spread.0 < LONG_APART {
return Err(Reject::TooShort);
}
// a big correction needs more than a few lines: three long lines and half the long lines'
// length agreeing (the folds of a gown spreading to the floor point at a far point too)
let tilt = if vertical { tilt_degrees(v) } else { 0.0 };
// consensus: real structure agrees; mirrored flanks (trees, peaks) split the family in two halves that each
// converge somewhere. Most of the family agreeing settles it; else the lines that disagree must not gather at
// a rival point of their own nearly as strongly (people, folds and foliage point every which way, so a few
// long posts among them still decide)
let mut family: f64 = segs.iter().map(Segment::len).sum();
// (judged on the long lines: a gown's many short folds don't outvote the posts around it)
let mut long_family: f64 = segs.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum();
let long_total: f64 = inl.iter().filter(|s| s.len() >= LONG_LINE).map(|s| s.len()).sum();
let share = if tilt > HUGE_TILT { 0.6 } else { 0.5 };
let big = tilt > BIG_TILT;
// Lines that meet inside or near the photo are scene features (floorboards running to the horizon, the
// apex of a drape, rays), never a camera tilt: they neither vote against the posts nor make a rival
// (the posts of a gazebo were outvoted by its deck and its curtains), and the big-tilt test below
// doesn't count them either.
let mut rival = 0.0;
if big || total < 0.6 * family {
let mut rest: Vec<Segment> = segs.iter().copied().filter(|s| vp_error(s, v) >= thr).collect();
for _ in 0..4 {
let Some((r, support)) = vanishing_point(&rest) else { break };
if !inside(r) {
rival = support;
break;
}
let (scene, other): (Vec<Segment>, Vec<Segment>) = rest.iter().partition(|s| vp_error(s, r) < thr);
if scene.is_empty() {
break;
}
family -= scene.iter().map(Segment::len).sum::<f64>();
long_family -= scene.iter().filter(|s| s.len() >= LONG_LINE).map(Segment::len).sum::<f64>();
rest = other;
}
}
if big && (long.len() < 3 || long_total < share * long_family) {
return Err(Reject::Disagree);
}
if total >= 0.6 * family {
return Ok(());
}
if total >= 0.3 * family && total >= 2.0 * rival {
return Ok(());
}
// most of the long lines agreeing settles it too (posts round a gown and its folds)
if long_total >= 0.6 * long_family {
return Ok(());
}
Err(Reject::Disagree)
}
/// Join the pieces of one straight edge (a post's side broken by a person in front of it, a branch, a
/// highlight) into one line, so a long structural edge counts as long: pieces on the same line (within 1.5°
/// and about 3 px at the analysis size) with a gap of at most a quarter of the half long edge between them.
fn merge_collinear(mut segs: Vec<Segment>) -> Vec<Segment> {
segs.sort_by(|a, b| b.len().total_cmp(&a.len()));
// each line: its first (longest) piece as the reference, and every piece joined to it
let mut lines: Vec<(Segment, Vec<Segment>)> = Vec::with_capacity(segs.len());
for s in segs {
let joined = lines.iter_mut().find(|(l, _)| collinear(l, &s));
match joined {
Some((l, pieces)) => {
pieces.push(s);
*l = fit_line(pieces).unwrap_or(*l);
}
None => lines.push((s, vec![s])),
}
}
lines.into_iter().map(|(l, _)| l).collect()
}
/// Whether piece `s` lies on line `l` (within 1.5° and about 3 px at the analysis size) with a gap of at most a
/// quarter of the half long edge between them.
fn collinear(l: &Segment, s: &Segment) -> bool {
let (dx, dy) = (l.b.x - l.a.x, l.b.y - l.a.y);
let n = dx.hypot(dy);
if n < 1e-9 {
return false;
}
inl.len() >= 3 && total >= 0.5 && hi - lo >= 0.4 && total >= 0.6 * family
let (ux, uy) = (dx / n, dy / n);
let (sx, sy) = (s.b.x - s.a.x, s.b.y - s.a.y);
let sn = sx.hypot(sy).max(1e-12);
if ((ux * sx + uy * sy) / sn).abs() < 1.5f64.to_radians().cos() {
return false;
}
let off = |p: Point| (p.x - l.a.x) * -uy + (p.y - l.a.y) * ux;
if off(s.a).abs() > 0.006 || off(s.b).abs() > 0.006 {
return false;
}
let t = |p: Point| (p.x - l.a.x) * ux + (p.y - l.a.y) * uy;
let (t0, t1) = (t(s.a).min(t(s.b)), t(s.a).max(t(s.b)));
(t0 - n).max(-t1).max(0.0) <= 0.25
}
/// The line through pieces (their endpoints weighted by the piece's length, principal axis), from end to end.
fn fit_line(pieces: &[Segment]) -> Option<Segment> {
let (mut sw, mut mx, mut my) = (0.0, 0.0, 0.0);
for s in pieces {
let w = s.len();
for p in [s.a, s.b] {
sw += w;
mx += w * p.x;
my += w * p.y;
}
}
if sw <= 0.0 {
return None;
}
let (mx, my) = (mx / sw, my / sw);
let (mut sxx, mut syy, mut sxy) = (0.0, 0.0, 0.0);
for s in pieces {
let w = s.len();
for p in [s.a, s.b] {
let (dx, dy) = (p.x - mx, p.y - my);
sxx += w * dx * dx;
syy += w * dy * dy;
sxy += w * dx * dy;
}
}
let th = 0.5 * (2.0 * sxy).atan2(sxx - syy);
let (ux, uy) = (th.cos(), th.sin());
let t = |p: Point| (p.x - mx) * ux + (p.y - my) * uy;
let (lo, hi) = pieces.iter().flat_map(|s| [t(s.a), t(s.b)]).fold((f64::MAX, f64::MIN), |(lo, hi), v| (lo.min(v), hi.max(v)));
Some(Segment { a: Point::new(mx + ux * lo, my + uy * lo), b: Point::new(mx + ux * hi, my + uy * hi) })
}
/// One family's vanishing point, if [`reliable`], else why not.
fn family_vp(segs: &[Segment], vertical: bool) -> (Option<[f64; 3]>, Option<Reject>) {
// a camera tilt puts the point outside the photo: look there first, so lines meeting inside it (a deck
// running to the horizon) can't take the place of the posts
let found = vanishing_point_where(segs, |v| !inside(v)).or_else(|| vanishing_point(segs));
match found {
None => (None, Some(Reject::TooFew)),
Some((v, _)) => match reliable(segs, v, vertical) {
Ok(()) => (Some(v), None),
// the strongest point may be one of many short pieces (foliage, folds) outweighing a few long posts:
// the long lines alone get their say, judged against the whole family (a short-only family stays out)
Err(Reject::TooShort) => {
let long: Vec<Segment> = segs.iter().copied().filter(|s| s.len() >= LONG_LINE).collect();
let again = (long.len() >= 2 && long.len() < segs.len())
.then(|| vanishing_point_where(&long, |v| !inside(v)).or_else(|| vanishing_point(&long)))
.flatten()
.filter(|(v, _)| reliable(segs, *v, vertical).is_ok());
match again {
Some((v, _)) => (Some(v), None),
None => (None, Some(Reject::TooShort)),
}
}
Err(why) => (None, Some(why)),
},
}
}
/// Group segments into near-vertical / near-horizontal families and find their vanishing points (only reliable
/// ones; see [`reliable`]).
pub fn analyze(segs: &[Segment]) -> Analysis {
let vertical: Vec<Segment> = segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect();
let horizontal: Vec<Segment> = segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect();
let vertical_vp = vanishing_point(&vertical).map(|v| v.0).filter(|v| reliable(&vertical, *v, true));
let horizontal_vp = vanishing_point(&horizontal).map(|v| v.0).filter(|v| reliable(&horizontal, *v, false));
Analysis { vertical, horizontal, vertical_vp, horizontal_vp }
let vertical = merge_collinear(segs.iter().copied().filter(|s| s.tilt_from_vertical() < 30.0).collect());
let horizontal = merge_collinear(segs.iter().copied().filter(|s| s.tilt_from_vertical() > 60.0).collect());
let (vertical_vp, vertical_why) = family_vp(&vertical, true);
let (horizontal_vp, horizontal_why) = family_vp(&horizontal, false);
Analysis { vertical, horizontal, vertical_vp, horizontal_vp, vertical_why, horizontal_why }
}
/// Why `mode` corrects less than it asks for on this analysis: `None` when it does what it says (or it is Off,
/// Guided or Auto with nothing to fix). In words for the user, after "No vertical correction: ".
pub fn shortfall(mode: Upright, a: &Analysis) -> Option<&'static str> {
match mode {
Upright::Vertical | Upright::Full if a.vertical_vp.is_none() => Some(a.vertical_why.unwrap_or(Reject::TooFew).message()),
Upright::Full if a.horizontal_vp.is_none() => Some(a.horizontal_why.unwrap_or(Reject::TooFew).message()),
Upright::Level if level_angle(&a.vertical, &a.horizontal).is_none() => {
let why = if a.vertical.is_empty() && a.horizontal.is_empty() { Reject::TooFew } else { Reject::Disagree };
Some(why.message())
}
Upright::Auto => auto(a).err().map(Reject::message),
_ => None,
}
}
/// What [`solve`] applies instead when `mode` falls short ([`shortfall`]) but corrects something all the same: Full
/// without a horizontal vanishing point straightens the verticals, and Vertical or Full without a vertical one levels.
/// In words for the user, after "No full correction: …. " (`None` when the result is no correction at all).
pub fn fallback(mode: Upright, a: &Analysis) -> Option<&'static str> {
let levels = || level_angle(&a.vertical, &a.horizontal).is_some_and(|d| d != 0.0);
match mode {
// verticals that already stand straight leave no correction to name
Upright::Full if a.vertical_vp.is_some() && a.horizontal_vp.is_none() => {
(solve(Upright::Full, a) != Homography::IDENTITY).then_some("Straightened the vertical lines instead")
}
Upright::Vertical | Upright::Full if a.vertical_vp.is_none() && levels() => Some("Levelled the photo instead"),
_ => None,
}
}
/// What to draw in Guided when `mode` falls short on `a` ("Try Guided: draw …"). Guided works from the guides
/// alone, not from lines the mode found, and one guide of a kind only levels ([`solve_guided`]): Full needs two of
/// each family, Vertical two vertical ones, and levelling one line. Auto follows why it stopped: a tilt more than
/// it levels ([`Reject::TooTilted`]) takes one guide of the family it levelled by (a level line for a horizon, an
/// upright one when only vertical lines were found); a vertical correction too steep for it
/// ([`Reject::TooSteep`]) needs two vertical guides, as one level line can't straighten converging posts; with too
/// few or unusable lines either can help, so it names both.
pub fn guided_hint(mode: Upright, a: &Analysis) -> &'static str {
const VERTICAL: &str = "two lines along what should be vertical";
match mode {
Upright::Full => "two lines along what should be vertical and two along what should be horizontal",
Upright::Level => "a line along what should be level or upright",
Upright::Auto => match auto(a) {
Err(Reject::TooTilted) if levels_by_vertical(&a.vertical, &a.horizontal) => "one line along what should be upright",
Err(Reject::TooTilted) => "one line along what should be level",
Err(Reject::TooSteep) => VERTICAL,
_ => "two lines along what should be vertical, or one line along what should be level",
},
_ => VERTICAL,
}
}
/// The Upright correction for `mode` from an analysis (lens-corrected → transformed, centred coordinates).
@@ -478,29 +772,49 @@ pub fn solve(mode: Upright, a: &Analysis) -> Homography {
Some((r, f)) => recentre(&rotation_homography(&r, f)),
None => vertical().map(|r| recentre(&rotation_homography(&r, DEFAULT_FOCAL))).unwrap_or_else(level),
},
Upright::Auto => {
// A vertical family that implies a camera roll must be confirmed by the horizontals (a real roll tilts
// both); otherwise it is scene structure (e.g. the same-side flanks of many conical trees).
if let Some(v) = a.vertical_vp {
let (x, y) = if v[1] < 0.0 { (-v[0], -v[1]) } else { (v[0], v[1]) };
let roll = x.atan2(y).to_degrees();
let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0);
if !confirmed {
let weaker = Analysis { vertical_vp: None, horizontal_vp: None, ..a.clone() };
return solve(Upright::Auto, &weaker);
}
}
// balanced: full correction only when it is moderate, else vertical, else level
if let Some((r, f)) = full().filter(|(r, _)| rotation_angle(r) < 20f64.to_radians()) {
return recentre(&rotation_homography(&r, f));
}
match vertical().filter(|r| rotation_angle(r) < 25f64.to_radians()) {
Some(r) => recentre(&rotation_homography(&r, DEFAULT_FOCAL)),
// conservative: only small horizon fixes; bigger tilts are usually intentional or scene lines
None => level_angle(&a.vertical, &a.horizontal).filter(|d| d.abs() <= 5.0).map(rot_z_h).unwrap_or(Homography::IDENTITY),
}
Upright::Auto => auto(a).unwrap_or(Homography::IDENTITY),
}
}
/// What Auto does with an analysis: the correction it applies, or why it applies none. [`solve`] and
/// [`shortfall`] both ask it, so the note always matches the correction.
fn auto(a: &Analysis) -> Result<Homography, Reject> {
// A vertical family that implies a camera roll must be confirmed by the horizontals (a real roll tilts
// both); otherwise it is scene structure (e.g. the same-side flanks of many conical trees).
if let Some(v) = a.vertical_vp {
let (x, y) = if v[1] < 0.0 { (-v[0], -v[1]) } else { (v[0], v[1]) };
let roll = x.atan2(y).to_degrees();
let confirmed = roll.abs() <= 3.0 || level_angle(&[], &a.horizontal).is_some_and(|h| (h - roll).abs() <= 3.0);
if !confirmed {
let weaker = Analysis { vertical_vp: None, horizontal_vp: None, vertical_why: Some(Reject::Disagree), ..a.clone() };
return auto(&weaker);
}
}
// balanced: full correction only when it is moderate, else vertical, else level
if let Some((v, h)) = a.vertical_vp.zip(a.horizontal_vp) {
let f = focal_from_vps(v, h).unwrap_or(DEFAULT_FOCAL);
let r = solve_full(v, h, f);
if rotation_angle(&r) < 20f64.to_radians() {
return Ok(recentre(&rotation_homography(&r, f)));
}
}
let vertical = a.vertical_vp.map(|v| solve_vertical(v, DEFAULT_FOCAL));
if let Some(r) = vertical.filter(|r| rotation_angle(r) < 25f64.to_radians()) {
return Ok(recentre(&rotation_homography(&r, DEFAULT_FOCAL)));
}
// conservative: only small horizon fixes; bigger tilts are usually intentional or scene lines
match level_angle(&a.vertical, &a.horizontal) {
Some(d) if d.abs() <= 5.0 => Ok(rot_z_h(d)),
_ if vertical.is_some() => Err(Reject::TooSteep),
Some(_) => Err(Reject::TooTilted),
// nothing to level by: a vertical family's own reason when it has one beyond a lack of lines, else lines
// that are there but don't agree, else too few lines
_ => Err(match a.vertical_why {
Some(why) if why != Reject::TooFew => why,
_ if a.vertical.is_empty() && a.horizontal.is_empty() => Reject::TooFew,
_ => Reject::Disagree,
}),
}
}
/// Guided Upright from user guides (centred coordinates of the lens-corrected image). Guides closer to vertical
@@ -563,6 +877,46 @@ pub fn analyze_source(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> A
a
}
/// [`analysis_plane`] at `long` px on its long edge (the evaluation examples read a larger one).
pub fn analysis_luminance(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, long: usize) -> Plane {
// Raw decoding keeps negative channels (noise near black through the camera matrix). Resampled as they are,
// they lower the luminance the segments are found in, so Upright would find a different correction than for
// the same photo decoded with its channels clipped at zero; it analyses that clipped source, as it always has.
let clipped;
let src = if src.data.iter().flatten().any(|v| *v < 0.0) {
clipped = src.map(|p| p.map(|v| v.max(0.0)));
&clipped
} else {
src
};
let mut base = s.clone();
base.geometry = Geometry::default();
base.crop = Crop::default();
let frame = crate::frame_for(src, info, &base, false);
let (w, h) = frame.fit(long, long);
let img = frame.sample(src, w, h);
let lum = img.luminance();
let mut v: Vec<f32> = lum.data.iter().copied().filter(|x| x.is_finite()).collect();
v.sort_by(f32::total_cmp);
let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4);
lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4))
}
/// Analyse an [`analysis_luminance`] plane of any size (brought to the analysis size first).
pub fn analyze_plane(lum: &Plane) -> Analysis {
analyze_plane_at(lum, ANALYSIS_LONG)
}
/// [`analyze_plane`] at `size` px on the long edge (at most the plane's own).
pub fn analyze_plane_at(lum: &Plane, size: usize) -> Analysis {
let long = lum.width.max(lum.height);
if long > size {
let fit = lightcraft_raster::resample::fit(lum, size, size, lightcraft_raster::resample::Filter::Box);
return analyze(&detect_segments(&fit));
}
analyze(&detect_segments(lum))
}
/// What an analysis depends on: the source (by its sampled fingerprint), the optics and
/// orientation settings, whether the optics section is on, and the lens the frame is corrected for
/// (`info.lens`, which [`analysis_plane`] reads through the frame).
@@ -579,27 +933,7 @@ pub(crate) fn analysis_key(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings)
/// The image an analysis reads: the lens-corrected source (optics applied, no perspective or crop)
/// at [`ANALYSIS_LONG`] px, as perceptual lightness normalized to its bright end.
pub(crate) fn analysis_plane(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings) -> Plane {
// Raw decoding keeps negative channels (noise near black through the camera matrix). Resampled as they are,
// they lower the luminance the segments are found in, so Upright would find a different correction than for
// the same photo decoded with its channels clipped at zero; it analyses that clipped source, as it always has.
let clipped;
let src = if src.data.iter().flatten().any(|v| *v < 0.0) {
clipped = src.map(|p| p.map(|v| v.max(0.0)));
&clipped
} else {
src
};
let mut base = s.clone();
base.geometry = Geometry::default();
base.crop = Crop::default();
let frame = crate::frame_for(src, info, &base, false);
let (w, h) = frame.fit(ANALYSIS_LONG, ANALYSIS_LONG);
let img = frame.sample(src, w, h);
let lum = img.luminance();
let mut v: Vec<f32> = lum.data.iter().copied().filter(|x| x.is_finite()).collect();
v.sort_by(f32::total_cmp);
let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4);
lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4))
analysis_luminance(src, info, s, ANALYSIS_LONG)
}
/// The crop angle (degrees, clockwise +) Auto straighten levels `src` by, if it finds a horizon or
@@ -643,3 +977,83 @@ pub fn homography(g: &Geometry, ow: f64, oh: f64) -> Homography {
_ => g.upright_transform.unwrap_or(Homography::IDENTITY),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Many short parallel pieces outweighing three long posts don't hide the posts' vanishing point: the long
/// lines are tried on their own when the strongest point has only short lines (CodeRabbit on #2966).
#[test]
fn short_pieces_outweighing_the_posts_do_not_hide_their_vanishing_point() {
let mut segs: Vec<Segment> = [-0.7, 0.0, 0.7].iter().map(|&x| Segment { a: Point::new(x, -0.8), b: Point::new(0.75 * x, 0.8) }).collect();
let (dx, dy) = (0.06 * 20f64.to_radians().sin(), 0.06 * 20f64.to_radians().cos());
for i in 0..60 {
let cx = -0.59 + 0.02 * i as f64;
segs.push(Segment { a: Point::new(cx - dx, -dy), b: Point::new(cx + dx, dy) });
}
let a = analyze(&segs);
assert!(a.vertical_vp.is_some(), "the posts give a vertical vanishing point: {:?}", a.vertical_why);
// short pieces alone still give none
let a = analyze(&segs[3..]);
assert!(a.vertical_vp.is_none());
}
/// Lines that are there but don't agree on a level say so, rather than that there are too few lines
/// (CodeRabbit on #2966).
#[test]
fn horizontals_that_disagree_are_reported_as_disagreeing() {
let segs: Vec<Segment> = [-4f64, 0.0, 4.0]
.iter()
.enumerate()
.map(|(i, d)| {
let (c, s) = (0.4 * d.to_radians().cos(), 0.4 * d.to_radians().sin());
let y = -0.5 + 0.5 * i as f64;
Segment { a: Point::new(-c, y - s), b: Point::new(c, y + s) }
})
.collect();
let a = analyze(&segs);
assert!(a.vertical.is_empty());
assert_eq!(auto(&a).err(), Some(Reject::Disagree));
}
/// The point refined from a candidate's lines is still held to the same test as the candidate: one that test
/// turns down leaves the candidate itself (CodeRabbit on #2966).
#[test]
fn a_refined_vanishing_point_the_test_refuses_falls_back_to_its_candidate() {
// three near-vertical lines that nearly, not exactly, meet far above the photo
let segs = [
Segment { a: Point::new(-0.5, -0.8), b: Point::new(-0.45, 0.8) },
Segment { a: Point::new(0.5, -0.8), b: Point::new(0.45, 0.8) },
Segment { a: Point::new(0.0, -0.8), b: Point::new(0.0003, 0.8) },
];
// only the candidates made from two of the lines pass; the least-squares point of all three does not
let candidates: Vec<[f64; 3]> = (0..3)
.flat_map(|i| (i + 1..3).map(move |j| (i, j)))
.flat_map(|(i, j)| [norm(cross(segs[i].line(), segs[j].line())), norm(cross(segs[j].line(), segs[i].line()))])
.collect();
let ok = |v: [f64; 3]| candidates.contains(&v);
let (v, _) = vanishing_point_where(&segs, ok).expect("a point");
assert!(ok(v), "{v:?} is not one of the candidates");
}
/// Long lines meeting inside the photo (floorboards, a drape) are scene features: they don't make a big
/// tilt's posts look outvoted (CodeRabbit on #2966).
#[test]
fn scene_lines_inside_the_photo_do_not_outvote_a_big_tilts_posts() {
// three posts leaning to a point far above the photo: a camera tilt of about 15 degrees
let v = norm([0.0, 5.6, 1.0]);
assert!(tilt_degrees(v) > BIG_TILT && tilt_degrees(v) < HUGE_TILT, "{}", tilt_degrees(v));
let toward = |x: f64, (px, py): (f64, f64), y1: f64| {
let t = (y1 + 0.8) / (py + 0.8);
Segment { a: Point::new(x, -0.8), b: Point::new(x + (px - x) * t, y1) }
};
let mut segs: Vec<Segment> = [-0.8, 0.0, 0.8].iter().map(|&x| toward(x, (0.0, 5.6), 0.8)).collect();
// six longer floor lines running to a point inside the photo, more length than the posts
segs.extend([-0.5, -0.35, -0.2, 0.2, 0.35, 0.5].iter().map(|&x| toward(x, (0.0, 0.9), 0.6)));
let posts: f64 = segs[..3].iter().map(Segment::len).sum();
let floor: f64 = segs[3..].iter().map(Segment::len).sum();
assert!(posts < 0.5 * (posts + floor), "the floor lines must outweigh the posts: {posts} vs {floor}");
assert_eq!(reliable(&segs, v, true), Ok(()));
}
}
+11 -2
View File
@@ -219,7 +219,8 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
(Upright::Full, "Full", "full"),
];
if let Some(mode) = crate::widgets::labeled_dropdown(ui, "upright", "Perspective Correction", "", &modes, d.geometry.upright) {
let _ = app.run("geometry.upright", json!({"mode": mode}));
let r = app.run("geometry.upright", json!({"mode": mode}));
upright_note(app, ui.ctx(), r.as_ref().ok());
// Guided starts drawing guides on the photo; any other mode stops it
app.ui.tool = if mode == Upright::Guided { "guidedUpright".into() } else { String::new() };
}
@@ -230,7 +231,8 @@ pub(super) fn crop(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
&& text_button(ui, "uprightUpdate", crate::i18n::tr("Update"), false).clicked()
{
let mode = serde_json::to_value(d.geometry.upright).unwrap_or_default();
let _ = app.run("geometry.upright", json!({"mode": mode}));
let r = app.run("geometry.upright", json!({"mode": mode}));
upright_note(app, ui.ctx(), r.as_ref().ok());
}
if guided {
let drawing = app.ui.tool == "guidedUpright";
@@ -472,3 +474,10 @@ pub(super) fn red_eye(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) {
});
});
}
/// Upright that found nothing to correct says why, as a note over the photo.
fn upright_note(app: &mut LightcraftApp, ctx: &egui::Context, result: Option<&serde_json::Value>) {
if let Some(note) = result.and_then(|r| r.get("note")).and_then(serde_json::Value::as_str) {
app.toast_for(ctx, note.to_string(), 8.0);
}
}
+5 -4
View File
@@ -36,7 +36,7 @@ every PR would edit and conflict on. A row marked ✅ that is wrong or incomplet
| C. Views & navigation (VIEW) | 16 | 1 | 1 | 0 | 9/9 (100%) | 4/4 (100%) |
| D. Search & filter (FILT) | 11 | 1 | 1 | 0 | 4/4 (100%) | 4/4 (100%) |
| E. Metadata (META) | 5 | 1 | 0 | 0 | 2/2 (100%) | 2/2 (100%) |
| F. Edit panel — global adjustments (EDIT) | 42 | 6 | 2 | 1 | 25/28 (89%) | 14/15 (93%) |
| F. Edit panel — global adjustments (EDIT) | 41 | 7 | 2 | 1 | 25/28 (89%) | 13/15 (87%) |
| G. Profiles (PROF) | 7 | 1 | 3 | 0 | 3/4 (75%) | 3/3 (100%) |
| H. Crop & rotate (CROP) | 10 | 1 | 0 | 1 | 8/8 (100%) | 2/3 (67%) |
| I. Remove / healing (REM) | 8 | 1 | 2 | 2 | 4/4 (100%) | 2/3 (67%) |
@@ -58,9 +58,9 @@ every PR would edit and conflict on. A row marked ✅ that is wrong or incomplet
| Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) |
| Z. Keyboard shortcuts (desktop) | 77 | 5 | 2 | 1 | 49/52 (94%) | 24/26 (92%) |
| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) |
| **Total** | 418 | 73 | 56 | 35 | 192/203 (95%) | 147/163 (90%) |
| **Total** | 417 | 74 | 56 | 35 | 192/203 (95%) | 146/163 (90%) |
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.1%** of 547 in-scope rows — P0 97.3% of 203 · P1 94.2% of 163 · P2 56.9% of 180.
Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.0%** of 547 in-scope rows — P0 97.3% of 203 · P1 93.9% of 163 · P2 56.9% of 180.
<!-- /parity:summary -->
## Top gaps and shortcut notes
@@ -223,7 +223,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
)
| LR-EDIT-OPTICS-DEFRINGE | Defringe | P1 | ✅ | `ctl:optics.defringe*` | no fringe eyedropper |
| LR-EDIT-OPTICS-MANUAL | Manual distortion / vignetting | P1 | ✅ | `ctl:optics.distortion`, `ctl:optics.vignetting`, `ctl:optics.vignettingMidpoint` | |
| LR-EDIT-GEOM-UPRIGHT | Upright | P1 | ✅ | `cmd:geometry.upright`, `cmd:geometry.guides` | |
| LR-EDIT-GEOM-UPRIGHT | Upright | P1 | 🟡 | `cmd:geometry.upright`, `cmd:geometry.guides`, `crates/pipeline/src/upright.rs` | a vertical family is accepted when most of it agrees, or when the lines that disagree (people, folds, foliage) gather at no rival point half as strong, so two long posts flanking a crowd decide (`upright_corrects_converging_posts_among_people`); a mode that finds nothing to correct says why (`note`, shown over the photo: too few / too short lines, one object, lines that disagree, lines meeting inside the photo) and suggests Guided. Downgraded from ✅: a user's real pavilion shots (thick posts, thin poles) were not corrected and the tuning is so far proven on synthetic scenes only; thin poles below a pixel at the 1024 px analysis size are still lost |
| LR-EDIT-GEOM-MANUAL | Manual transform | P1 | ✅ | `ctl:geometry.*` | |
| LR-EDIT-GEOM-CONSTRAIN | Constrain crop | P1 | ✅ | `crates/ui-egui/src/panels/right.rs` (checkbox → `cmd:develop.merge`), `crates/engine/src/lib.rs` (`fit_constrained_crop`) | Ticking it, or changing Geometry, Upright or lens corrections while it is ticked, shrinks the stored crop about its centre until no blank corner is left, so the Crop tool shows it (it used to apply at render time only, outside the Crop tool: issue #1927; tests in `crates/engine/src/tests/constrain_crop.rs`). A crop drawn by hand is kept as drawn; unticking keeps the tighter crop |
| LR-EDIT-GEOM-GRID | Grid while transforming | P2 | ✅ | `crates/ui-egui/src/panels/detail.rs` | a fine grid over the photo while a geometry slider is dragged |
@@ -835,6 +835,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
| 2026-10-31 | patch | LR-MASK-OVERLAY: the pointer on a mask's own row (name, eye, menu) shows no overlay, so its eye judges the effect; a component row under it shows the whole mask's overlay; status unchanged (✅) |
| 2026-10-25 | minor | LR-MASK-OVERLAY: one overlay rule (O / the eye, or the pointer on the mask's row or pin while nothing is adjusted, or a mask without settings yet); a mask with settings never shows by itself, so picking, creating, duplicating or adding to one no longer shows the overlay (#1800's re-show replaced, its test changed to the rule); sliders, mask drags and brush strokes hide it and the mask's lines and pins while at work; no stand-in overlay while an AI selection is computed; status unchanged (✅) |
| 2026-10-25 | minor | LR-EDIT-COLOR-MIXER-HSL: Lightroom Classic's layout (Mixer \| Point Color tabs, Adjust HSL / Color, Hue \| Saturation \| Luminance \| All with a targeted adjustment per group), `view.colorMixer`; status unchanged (✅) |
| 2026-10-25 | minor | LR-EDIT-GEOM-UPRIGHT: ✅ → 🟡 (real shots of posts among people were not corrected; tuned on synthetic scenes only): a vertical family wins over a crowd of disagreeing lines unless they gather at a rival point, Vertical follows long posts rather than decks, drapes or gown folds; a mode that finds nothing says why |
| 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca |
| 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged |
| 2026-10-25 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K / Ctrl+Alt+Shift+K (`dialog.keywordShortcut`, Set Keyword Shortcut) and ⇧K (`keyword.toggleShortcut`) add and remove the keyword shortcut's keywords; Keyword Shortcut leaves LRC-LIB-KEYWORDS' Not yet list; status counts unchanged (KEYC-METADATA stays 🟡) |