From 9614f9e1a387b228c94bd49a025f8347adae9f15 Mon Sep 17 00:00:00 2001 From: 1234destiny1234 <180862339+1234destiny1234@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:15:36 +0000 Subject: [PATCH 1/2] Reduce false face detections and expose confidence sensitivity Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/engine/src/cmd/face_detect.rs | 16 +++++++-- crates/engine/src/cmd/face_models.rs | 50 ++++++++++++++++++++++++++-- crates/tflite/src/mediapipe.rs | 39 ++++++++++++++++++++++ crates/ui-egui/src/panels/faces.rs | 11 ++++++ docs/faces.md | 20 +++++++++++ 5 files changed, 132 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/face_detect.rs b/crates/engine/src/cmd/face_detect.rs index f629508a23..87a1ae059f 100644 --- a/crates/engine/src/cmd/face_detect.rs +++ b/crates/engine/src/cmd/face_detect.rs @@ -57,6 +57,8 @@ impl NoDetector { pub(crate) struct Finder { #[cfg(feature = "sam")] model: Arc, + #[cfg(feature = "sam")] + score: f32, } impl Finder { @@ -93,10 +95,19 @@ impl Finder { } let mut out = Vec::new(); for d in dets { + // Reject tiny/weak candidates before running the expensive landmark model. + if d.score < self.score || d.width().min(d.height()) < 24.0 { + continue; + } let landmarks = self.model.landmarks(rgb, w, h, &d).map_err(|e| e.to_string())?; // FaceMesh not seeing a face there, and the detector only fairly sure: a pattern, a paw, a circuit // board (the detector alone takes those for faces, mostly in the tiles of `fine`) - if landmarks.is_none() && d.score < lcc_segment::people::FACE_THRESHOLD_NO_MESH { + if landmarks.is_none() && d.score < 0.9 { + continue; + } + // A retry crop can lock onto a neighbouring face. Never attach that person's + // embedding to this box (for example a false detection on their hand). + if landmarks.as_ref().is_some_and(|lm| !mediapipe::landmarks_match_detection(&d, lm)) { continue; } let found = crate::segment::FoundFace::from_pixels(&lcc_segment::people::Face { detection: d, landmarks }, w as f32, h as f32); @@ -129,7 +140,8 @@ pub(crate) fn detector(s: &Session) -> std::result::Result, NoDetect let model = crate::segment::face_model(&dir).map_err(NoDetector::Unusable)?; #[cfg(not(target_arch = "wasm32"))] offer_detection_gpu(s, &model); - Ok(Arc::new(Finder { model })) + let score = s.face_models_dir.as_deref().map(super::face_models::read_settings).unwrap_or_default().detection_score(); + Ok(Arc::new(Finder { model, score })) } #[cfg(not(feature = "sam"))] { diff --git a/crates/engine/src/cmd/face_models.rs b/crates/engine/src/cmd/face_models.rs index 7867e34b6c..12e8884dad 100644 --- a/crates/engine/src/cmd/face_models.rs +++ b/crates/engine/src/cmd/face_models.rs @@ -51,6 +51,13 @@ pub(super) struct FaceSettings { /// theirs ([`lcc_faces::matching::typical`]). Off unless the user turns it on. #[serde(deserialize_with = "lenient_bool", skip_serializing_if = "std::ops::Not::not")] pub(super) skip_odd: bool, + /// Detector confidence floor; absent or malformed settings use the conservative default. + #[serde(deserialize_with = "lenient_score", skip_serializing_if = "Option::is_none")] + pub(super) detection_score: Option, +} + +fn lenient_score<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result, D::Error> { + Ok(Value::deserialize(d)?.as_f64().filter(|n| (0.65f32..=0.95f32).contains(&(*n as f32))).map(|n| n as f32)) } /// A saved switch that is not true or false is off, for the same reason as [`lenient_count`]. @@ -65,6 +72,10 @@ fn lenient_count<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result< } impl FaceSettings { + pub(super) fn detection_score(&self) -> f32 { + self.detection_score.unwrap_or(0.75) + } + /// Whether a scan averages each face with its mirror image (the default). pub(super) fn mirror_average(&self) -> bool { !self.no_mirror @@ -165,7 +176,22 @@ fn matching(s: &mut Session, p: &Value) -> Result { let top = p.get("topFaces").map(|v| top_faces_value(C, v, "the default")).transpose()?; let mirror = p.get("mirrorAverage").map(|v| v.as_bool().ok_or_else(|| bad(C, "`mirrorAverage` is true or false"))).transpose()?; let skip_odd = p.get("skipOdd").map(|v| v.as_bool().ok_or_else(|| bad(C, "`skipOdd` is true or false"))).transpose()?; - if top.is_some() || skip_odd.is_some() { + let detection_score = p + .get("detectionScore") + .map(|v| { + if v.is_null() { + return Ok(None); + } + v.as_f64() + .filter(|n| (0.65f32..=0.95f32).contains(&(*n as f32))) + .map(|n| Some(n as f32)) + .ok_or_else(|| bad(C, "`detectionScore` is 0.65 to 0.95, or null for the default")) + }) + .transpose()?; + if top.is_some() || skip_odd.is_some() || detection_score.is_some() { + if let Some(score) = detection_score { + st.detection_score = score; + } if let Some(top) = top { st.top_faces = top; } @@ -194,6 +220,7 @@ fn matching(s: &mut Session, p: &Value) -> Result { "topFacesMax": lcc_faces::matching::MAX_TOP_FACES, "mirrorAverage": st.mirror_average(), "skipOdd": st.skip_odd, + "detectionScore": st.detection_score(), })) } @@ -364,6 +391,7 @@ fn list(s: &mut Session, _: &Value) -> Result { "mirrorAverage": settings.mirror_average(), // a person's odd faces are left out when looking for faces like theirs (`faces.matching`) "skipOdd": settings.skip_odd, + "detectionScore": settings.detection_score(), // where the models run: {cpuOnly, detection, recognition} as `faces.gpu` gives it "gpu": super::face_detect::gpu_json(s), // Native builds always have the pure-Rust runner; model files/background scanning remain native-only. @@ -739,6 +767,24 @@ pub fn specs() -> Vec { cmd!(query "faces.models.remove", "Remove Face Model", [], None, "{id}: delete an installed model", always, remove), cmd!(query "faces.models.select", "Choose Face Recognition Model", [], None, "{id: installed recogniser | null}", always, select), cmd!(query "faces.enable", "Face Recognition On/Off", [], None, "{enabled?: bool} (toggles when omitted)", always, enable), - cmd!(query "faces.matching", "Face Matching", [], None, "{topFaces?: 1..8 | null, mirrorAverage?: bool, skipOdd?: bool} → {topFaces, topFacesDefault, topFacesMax, mirrorAverage, skipOdd}: `mirrorAverage` (default true) makes a scan average each face with its mirror image, which matches slightly more often and takes twice as long to scan (faces embedded the other way are embedded again when it changes). `topFaces`: how many of a person's best matching faces a suggestion's score is the mean of (Settings ▸ Faces; null goes back to the default). More faces make two odd photos of someone (blurred, in profile) less able to carry a stranger. Only the scores of people with more faces than the count before can fall: a person with fewer faces is scored on the ones they have. `skipOdd` leaves a person's odd faces (far from their average face: from behind, misnamed) out when their page looks for faces like theirs (off by default)", always, matching), + cmd!(query "faces.matching", "Face Matching", [], None, "{topFaces?: 1..8 | null, mirrorAverage?: bool, skipOdd?: bool, detectionScore?: 0.65..0.95 | null} → {topFaces, topFacesDefault, topFacesMax, mirrorAverage, skipOdd, detectionScore}: `detectionScore` sets the confidence required for future detections (0.75 by default; higher finds fewer false faces, null restores the default). `mirrorAverage` (default true) makes a scan average each face with its mirror image, which matches slightly more often and takes twice as long to scan (faces embedded the other way are embedded again when it changes). `topFaces`: how many of a person's best matching faces a suggestion's score is the mean of (Settings ▸ Faces; null goes back to the default). More faces make two odd photos of someone (blurred, in profile) less able to carry a stranger. Only the scores of people with more faces than the count before can fall: a person with fewer faces is scored on the ones they have. `skipOdd` leaves a person's odd faces (far from their average face: from behind, misnamed) out when their page looks for faces like theirs (off by default)", always, matching), ] } + +#[cfg(test)] +mod sensitivity_tests { + use super::*; + + #[test] + fn sensitivity_defaults_and_bad_values_preserve_other_settings() { + for value in [json!(null), json!("high"), json!(-1), json!(1.2)] { + let st: FaceSettings = serde_json::from_value(json!({"enabled": true, "detectionScore": value})).unwrap(); + assert!(st.enabled); + assert_eq!(st.detection_score(), 0.75); + } + let st: FaceSettings = serde_json::from_value(json!({"detectionScore": 0.85})).unwrap(); + assert_eq!(st.detection_score(), 0.85); + let copy: FaceSettings = serde_json::from_value(serde_json::to_value(st).unwrap()).unwrap(); + assert_eq!(copy.detection_score(), 0.85); + } +} diff --git a/crates/tflite/src/mediapipe.rs b/crates/tflite/src/mediapipe.rs index 4549e67e56..31269dae1e 100644 --- a/crates/tflite/src/mediapipe.rs +++ b/crates/tflite/src/mediapipe.rs @@ -93,6 +93,28 @@ impl Detection { } } +/// Whether a mesh still describes this detection, rather than a neighbour caught by a +/// retry crop. Use the oval centre and size, not eye ordering (profiles and roll are valid). +pub fn landmarks_match_detection(d: &Detection, lm: &[[f32; 2]]) -> bool { + if lm.len() != MESH_POINTS || !lm.iter().flatten().all(|v| v.is_finite()) { + return false; + } + let mut b = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY]; + for i in FACE_OVAL { + let p = lm[i]; + b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]; + } + let [cx, cy] = d.center(); + let size = d.width().max(d.height()); + let mesh_size = (b[2] - b[0]).max(b[3] - b[1]); + size.is_finite() + && size > 0.0 + && ((b[0] + b[2]) * 0.5 - cx).abs() <= d.width() * 0.5 + && ((b[1] + b[3]) * 0.5 - cy).abs() <= d.height() * 0.5 + && mesh_size >= size * 0.4 + && mesh_size <= size * 2.0 +} + /// BlazeFace short range's 896 anchor centres (normalized): 16 × 16 cells × 2 at stride 8, then /// 8 × 8 cells × 6 at stride 16 (MediaPipe's SSD anchor options for this model). pub fn blazeface_anchors() -> Vec<[f32; 2]> { @@ -890,6 +912,23 @@ pub fn selfie_softmax(logits: &[f32]) -> Vec { mod tests { use super::*; + #[test] + fn mesh_confirmation_cannot_jump_to_a_neighbour() { + let d = Detection { x0: 100.0, y0: 100.0, x1: 200.0, y1: 200.0, score: 0.9, keypoints: [[0.0; 2]; 6] }; + let mut lm = vec![[150.0, 150.0]; MESH_POINTS]; + for (k, i) in FACE_OVAL.iter().enumerate() { + let a = k as f32 * std::f32::consts::TAU / FACE_OVAL.len() as f32; + lm[*i] = [150.0 + 45.0 * a.cos(), 150.0 + 60.0 * a.sin()]; + } + assert!(landmarks_match_detection(&d, &lm)); + let moved: Vec<_> = lm.iter().map(|p| [p[0] + 100.0, p[1]]).collect(); + assert!(!landmarks_match_detection(&d, &moved)); + assert!(!landmarks_match_detection(&d, &lm[..10])); + assert!(!landmarks_match_detection(&d, &vec![[150.0; 2]; MESH_POINTS])); + lm[0][0] = f32::NAN; + assert!(!landmarks_match_detection(&d, &lm)); + } + #[test] fn anchors_and_decoding() { let a = blazeface_anchors(); diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index f6c366d215..0a484d2c49 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -175,6 +175,17 @@ pub fn setup_banner(app: &mut LccApp, ui: &mut egui::Ui) { /// The switch for averaging each face with its mirror image: a little steadier matching for twice the scanning time. fn mirror_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, list: &Value) { + heading(ui, t, "Detection sensitivity"); + let mut score = list["detectionScore"].as_f64().unwrap_or(0.75) as f32; + let r = ui.add(egui::Slider::new(&mut score, 0.65..=0.95).text(crate::i18n::tr("Confidence required"))); + register(ui.ctx(), "slider:settings.facesDetectionScore", r.rect); + if r.changed() { + match app.run("faces.matching", json!({"detectionScore": score})) { + Ok(_) => app.caches.faces_epoch += 1, + Err(e) => app.toast_error(ui.ctx(), e), + } + } + hint(ui, t, "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections."); heading(ui, t, "Matching"); let mut on = list["mirrorAverage"].as_bool().unwrap_or(true); let r = crate::dialog_frame::in_control_column(ui, |ui| ui.checkbox(&mut on, crate::i18n::tr("Average each face with its mirror image"))); diff --git a/docs/faces.md b/docs/faces.md index cd5f8c9b38..8d2ac96a31 100644 --- a/docs/faces.md +++ b/docs/faces.md @@ -578,3 +578,23 @@ thread with a row in the activity stack in the app, at once in the CLI and MCP ( Without the models the AI Models dialog offers them; nothing is downloaded on its own. The sliders and the person are develop controls (`retouch.teethWhiten`, `retouch.teethBrighten`, `retouch.teethPerson`) in the **Retouch** settings group; copy, paste, sync and presets never carry another photo's teeth. Teeth has its own eye for a before/after. + + +### Reducing false face detections + +Settings ▸ Faces includes **Detection sensitivity / Confidence required**. The default +confidence is 0.75; raise it (up to 0.95) to favour precision, or lower it (down to +0.65) to recover harder faces. CLI/MCP clients can use +`faces.matching {"detectionScore": 0.85}` (`null` restores the default). +The setting applies to both Detect Faces and future background scans. It does not +silently remove existing regions: use the existing clear/rescan controls to review +old automatic detections; named and manually added regions are preserved. + +Candidates smaller than 24 pixels on either side in the detector input are dropped +before landmark fitting or recognition. A detection without FaceMesh confirmation +requires at least 0.90 confidence, and a mesh that has drifted onto a neighbouring +face is rejected rather than associated with the original box. These are conservative +quality gates, not proof that an object is a live person: faces in posters and photos +can still be detected. Ignore those regions explicitly. Similar-looking people can +still need manual correction; these detection controls do not change identity matching +thresholds or overwrite confirmed names. From 223757201259b7162573d2d69f515c1e2e0615ca Mon Sep 17 00:00:00 2001 From: 1234destiny1234 <180862339+1234destiny1234@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:23:05 +0000 Subject: [PATCH 2/2] Issue #1444: fix face sensitivity hint formatting Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- crates/ui-egui/src/panels/faces.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/panels/faces.rs b/crates/ui-egui/src/panels/faces.rs index 0a484d2c49..8aa16a75c5 100644 --- a/crates/ui-egui/src/panels/faces.rs +++ b/crates/ui-egui/src/panels/faces.rs @@ -185,7 +185,11 @@ fn mirror_section(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens, list: &Value) Err(e) => app.toast_error(ui.ctx(), e), } } - hint(ui, t, "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections."); + hint( + ui, + t, + "Higher confidence finds fewer false faces, but may miss real faces. Applies to future detections; rescan to update existing detections.", + ); heading(ui, t, "Matching"); let mut on = list["mirrorAverage"].as_bool().unwrap_or(true); let r = crate::dialog_frame::in_control_column(ui, |ui| ui.checkbox(&mut on, crate::i18n::tr("Average each face with its mirror image")));