Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Select › Color Range: Skin Tones (#4473)

Gert Pellin - GPEd3d86da130b9
diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs
index d6662e75f..ad858df2a 100644
--- a/crates/algo/src/selection.rs
+++ b/crates/algo/src/selection.rs
@@ -698,6 +698,40 @@ pub fn hue_range(px: &[[f32; 4]], center: f32) -> Vec<f32> {
.collect()
}
+/// Color Range › Select: Skin Tones. Skin of every complexion falls in a compact region of the
+/// YCbCr chroma plane (Chai & Ngan, "Face segmentation using skin-color map", 1999: Cb about
+/// 77..127, Cr about 133..173, Rec. 601 on 0..255) that runs from pale (higher Cb, lower Cr) to
+/// saturated (lower Cb, higher Cr). Pixels inside an ellipse along that run are fully selected;
+/// outside, selection falls off linearly over `fuzziness` (0..200, as the dialog's Fuzziness: 100
+/// is one ellipse radius). Pale neutrals such as cream or beige sit just off its pale end, so they
+/// stay out. Near-black and near-white pixels, whose chroma is noise, are faded out.
+pub fn skin_tones(px: &[[f32; 4]], fuzziness: f32) -> Vec<f32> {
+ const CB: f32 = 104.0;
+ const CR: f32 = 158.0;
+ /// Radii along the run and across it, and the run's angle from the Cb axis.
+ const ALONG: f32 = 22.0;
+ const ACROSS: f32 = 14.0;
+ const ANGLE: f32 = -40.0;
+ let (sin, cos) = ANGLE.to_radians().sin_cos();
+ let ramp = (fuzziness / 100.0).max(1e-3);
+ px.iter()
+ .map(|&[r, g, b, a]| {
+ if a <= 0.0 {
+ return 0.0;
+ }
+ let [r, g, b] = [r, g, b].map(|v| v.clamp(0.0, 1.0) * 255.0);
+ let y = 0.299 * r + 0.587 * g + 0.114 * b;
+ let cb = 128.0 - 0.168_736 * r - 0.331_264 * g + 0.5 * b - CB;
+ let cr = 128.0 + 0.5 * r - 0.418_688 * g - 0.081_312 * b - CR;
+ let d = ((cos * cb + sin * cr) / ALONG).hypot((cos * cr - sin * cb) / ACROSS);
+ let chroma = (1.0 - (d - 1.0) / ramp).clamp(0.0, 1.0);
+ let dark = ((y - 25.0) / 30.0).clamp(0.0, 1.0);
+ let bright = ((250.0 - y) / 20.0).clamp(0.0, 1.0);
+ chroma * dark * bright
+ })
+ .collect()
+}
+
/// Color Range › Select: Highlights, Midtones or Shadows. Pixels whose luminance (Rec. 601
/// weights, 0..255) lies in `lo..=hi` are fully selected; outside, selection falls off linearly
/// to 0 over `falloff` levels (the dialog's Fuzziness).
@@ -908,6 +942,28 @@ mod tests {
}
}
+ #[test]
+ fn skin_tones_selects_skin_and_not_cream_or_white() {
+ let px = |rgb: [u8; 3]| [rgb[0], rgb[1], rgb[2]].map(|v| f32::from(v) / 255.0);
+ let rgba = |rgb: [u8; 3]| {
+ let [r, g, b] = px(rgb);
+ [r, g, b, 1.0]
+ };
+ // Skin in light and shadow, then a cream shirt, a near-white wall, blue denim and black.
+ let skin =
+ [[183, 119, 81], [177, 132, 93], [180, 121, 84], [120, 76, 52], [173, 107, 75], [255, 219, 172], [194, 140, 104], [141, 85, 36], [92, 51, 23]]
+ .map(rgba);
+ let m = skin_tones(&skin, 40.0);
+ assert!(m.iter().all(|&v| v > 0.95), "skin {m:?}");
+ let other = [[231, 225, 202], [252, 253, 247], [40, 60, 110], [5, 5, 5], [128, 128, 128], [220, 40, 40], [200, 160, 40]].map(rgba);
+ let m = skin_tones(&other, 40.0);
+ assert!(m.iter().all(|&v| v < 0.05), "not skin {m:?}");
+ // Fuzziness widens the region; transparent pixels are never selected.
+ let pale = [rgba([230, 215, 200])];
+ assert!(skin_tones(&pale, 200.0)[0] > skin_tones(&pale, 0.0)[0]);
+ assert_eq!(skin_tones(&[[0.7, 0.45, 0.3, 0.0]], 40.0), vec![0.0]);
+ }
+
#[test]
fn color_range_falloff() {
let px = vec![[1.0, 0.0, 0.0, 1.0], [0.9, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 0.0]];
diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs
index e92a8fd5c..c59d1a453 100644
--- a/crates/engine/src/selection_cmds.rs
+++ b/crates/engine/src/selection_cmds.rs
@@ -360,6 +360,10 @@ fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
let invert = b(p, "invert", false);
let selection_mode = mode(p);
let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0);
+ // Photoshop's Detect Faces needs a face detector, which there is none of yet (#4455).
+ if b(p, "detectFaces", false) {
+ return Err(bad("detectFaces: face detection isn't available yet; select without it".into()));
+ }
let (area, mut mask) = match preset {
"sampledColors" => {
let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?;
@@ -385,6 +389,10 @@ fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?;
(area, sel::hue_range(&px, center))
}
+ "skinTones" => {
+ let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?;
+ (area, sel::skin_tones(&px, fuzz(40.0).min(200.0)))
+ }
"highlights" | "midtones" | "shadows" => {
// Range in levels (Highlights / Shadows: one value, Midtones: [low, high]); Fuzziness
// is a percentage of the tonal scale.
@@ -418,7 +426,7 @@ fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
}
other => {
return Err(bad(format!(
- "unknown select `{other}` (sampledColors, reds, yellows, greens, cyans, blues, magentas, highlights, midtones, shadows, outOfGamut)"
+ "unknown select `{other}` (sampledColors, reds, yellows, greens, cyans, blues, magentas, highlights, midtones, shadows, skinTones, outOfGamut)"
)));
}
};
@@ -623,7 +631,7 @@ pub fn specs() -> Vec<CommandSpec> {
"select.colorRange",
"Color Range…",
["Select"],
- r##"{"select":"sampledColors|reds|yellows|greens|cyans|blues|magentas|highlights|midtones|shadows|outOfGamut"="sampledColors","color":"#rrggbb"=foreground,"colors":["#rrggbb",…]?,"points":[[x,y],…]? (eyedropper samples),"subtractPoints":[[x,y],…]? (minus eyedropper),"order":["+"|"-",…]? (click order of points and subtractPoints; default all points first),"fuzziness":0..200=40 (tones: 0..100 %=20),"localized":bool=false,"range":0..100=100 (% of the longer side),"tonalRange":level|[lo,hi] (shadows 65, highlights 190, midtones [105,150]),"invert":bool=false,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##,
+ r##"{"select":"sampledColors|reds|yellows|greens|cyans|blues|magentas|highlights|midtones|shadows|skinTones|outOfGamut"="sampledColors","color":"#rrggbb"=foreground,"colors":["#rrggbb",…]?,"points":[[x,y],…]? (eyedropper samples),"subtractPoints":[[x,y],…]? (minus eyedropper),"order":["+"|"-",…]? (click order of points and subtractPoints; default all points first),"fuzziness":0..200=40 (tones: 0..100 %=20),"detectFaces":bool=false (not available yet: refused),"localized":bool=false,"range":0..100=100 (% of the longer side),"tonalRange":level|[lo,hi] (shadows 65, highlights 190, midtones [105,150]),"invert":bool=false,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##,
has_doc,
color_range
),
@@ -692,6 +700,30 @@ mod tests {
}
}
+ #[test]
+ fn color_range_skin_tones_selects_skin_not_cream_and_refuses_detect_faces() {
+ let mut s = session();
+ let rgb = |c: [u8; 3]| [f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 1.0];
+ s.edit("paint", |doc, _| {
+ let bg = doc.layers[0].surface_mut().unwrap();
+ bg.fill_rect(Rect::new(0, 0, 40, 30), &rgb([252, 253, 247]));
+ bg.fill_rect(Rect::new(5, 5, 15, 15), &rgb([183, 119, 81]));
+ bg.fill_rect(Rect::new(25, 5, 35, 15), &rgb([231, 225, 202]));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("select.colorRange", json!({"select": "skinTones"})).unwrap();
+ assert!(coverage(&s, 10, 10) > 0.95, "skin");
+ assert!(coverage(&s, 30, 10) < 0.05, "cream");
+ assert!(coverage(&s, 2, 2) < 0.05, "near-white background");
+ // Subtracting skin from a selection of both squares keeps only the cream one.
+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 30, "height": 10})).unwrap();
+ s.execute("select.colorRange", json!({"select": "skinTones", "mode": "subtract"})).unwrap();
+ assert!(coverage(&s, 10, 10) < 0.05 && coverage(&s, 30, 10) > 0.95, "{} {}", coverage(&s, 10, 10), coverage(&s, 30, 10));
+ let err = s.execute("select.colorRange", json!({"select": "skinTones", "detectFaces": true})).unwrap_err();
+ assert!(err.to_string().contains("detectFaces"), "{err}");
+ }
+
#[test]
fn color_range_replace_is_bounded_by_existing_selection() {
for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] {
diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/color_range_ui.rs
index 37c90c18e..80417eeec 100644
--- a/crates/ui-egui/src/color_range_ui.rs
+++ b/crates/ui-egui/src/color_range_ui.rs
@@ -25,8 +25,7 @@ use crate::widgets;
/// The engine command the dialog drives.
pub const COMMAND: &str = "select.colorRange";
-/// Select menu entries in Photoshop's order (engine value, label). Skin Tones is left out: the
-/// engine has no skin-tone model.
+/// Select menu entries in Photoshop's order (engine value, label).
pub const SELECTS: &[(&str, &str)] = &[
("sampledColors", "Sampled Colors"),
("reds", "Reds"),
@@ -38,6 +37,7 @@ pub const SELECTS: &[(&str, &str)] = &[
("highlights", "Highlights"),
("midtones", "Midtones"),
("shadows", "Shadows"),
+ ("skinTones", "Skin Tones"),
("outOfGamut", "Out Of Gamut"),
];
@@ -82,7 +82,7 @@ pub fn controls(f: &Map<String, Value>) -> Controls {
let select = s(f, "select", "sampledColors");
let sampled = select == "sampledColors";
let tonal = matches!(select, "highlights" | "midtones" | "shadows");
- Controls { fuzziness: sampled || tonal, sampling: sampled, range: sampled && flag(f, "localized"), tonal }
+ Controls { fuzziness: sampled || tonal || select == "skinTones", sampling: sampled, range: sampled && flag(f, "localized"), tonal }
}
/// Open the dialog with Photoshop's defaults (Sampled Colors, Fuzziness 40, the foreground colour
@@ -141,6 +141,8 @@ pub fn params(f: &Map<String, Value>) -> Value {
p.insert("localized".into(), json!(true));
p.insert("range".into(), json!(num(f, "range", 100.0)));
}
+ } else if select == "skinTones" {
+ p.insert("fuzziness".into(), json!(num(f, "fuzziness", 40.0)));
} else if c.tonal {
p.insert("fuzziness".into(), json!(num(f, "toneFuzziness", 20.0)));
let range = match select {
@@ -942,6 +944,11 @@ mod tests {
assert!(h.query_by_label("Midtones from:").is_some() && h.query_by_label("Midtones to:").is_some());
set(&mut h, "select", json!("outOfGamut"));
assert!(disabled(&h, "Fuzziness:") && h.query_by_label("Midtones from:").is_none());
+ // Skin Tones: Fuzziness (the colour one), no eyedroppers or clusters.
+ set(&mut h, "select", json!("skinTones"));
+ assert!(!disabled(&h, "Fuzziness:") && disabled(&h, "Localized Color Clusters") && disabled(&h, "Add to Sample"));
+ let skin: Map<String, Value> = serde_json::from_value(json!({"select": "skinTones", "fuzziness": 25.0, "points": [[1, 1]]})).unwrap();
+ assert_eq!(params(&skin), json!({"select": "skinTones", "invert": false, "fuzziness": 25.0}));
assert_eq!(
controls(&serde_json::from_value(json!({"select": "highlights"})).unwrap()),
Controls { fuzziness: true, sampling: false, range: false, tonal: true }