PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Histogram: count the document's pixels, not a blurred thumbnail (#6538) (#6724)
David Mann566dbb3f83ec
diff --git a/crates/ui-egui/src/tone.rs b/crates/ui-egui/src/tone.rsindex aaf742096..f02c108db 100644--- a/crates/ui-egui/src/tone.rs+++ b/crates/ui-egui/src/tone.rs@@ -24,6 +24,9 @@ static EMPTY: [u32; 256] = [0; 256];pub struct Histograms {pub tag: u64,pub ch: Vec<[u32; 256]>,+ /// Photoshop's histogram cache level of a composite histogram: 1 when every document pixel+ /// was counted, `n` when a proxy 2^(n-1) times smaller stood in; 0 for a gray plane's.+ pub level: u32,}impl std::ops::Index<usize> for Histograms {@@ -76,6 +79,7 @@ fn isolate(layers: &mut [Layer], id: LayerId) -> bool {/// Histograms of `doc` as seen by `source`, in the channels of `space`.pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace) -> Histograms {+ let mut level = 0;let mut h = vec![[0u32; 256];match space {@@ -100,14 +104,23 @@ pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace)}}HistSource::BelowLayer(_) | HistSource::Layer(_) => {- composite_bins(doc, source, space, &mut h);+ level = composite_bins(doc, source, space, &mut h);}}- Histograms { tag: tag(source, space), ch: h }+ Histograms { tag: tag(source, space), ch: h, level }}/// Bins of the composited image below (`BelowLayer`) or of one layer alone (`Layer`), in `space`.-fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut [[u32; 256]]) {+/// Returns the cache level counted: 1 when every document pixel was counted, higher when a+/// downsampled proxy stood in (like Photoshop's histogram cache levels).+///+/// The pixels are counted as they are, never blended: an area-averaged thumbnail invented greys+/// that aren't in the image wherever an edge fell inside one of its cells (#6538). Documents up to+/// [`photocraft_compose::PROXY_THUMBNAIL_PIXELS`] (and those a proxy can't reduce faithfully) are+/// composited in bands and counted exactly, which costs what the thumbnail did (it reduced the+/// same full composite). Larger ones count a nearest-neighbour proxy composite of about the old+/// thumbnail's work: it only holds values the layers have.+fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut [[u32; 256]]) -> u32 {let mut d = doc.clone();match source {HistSource::BelowLayer(hide) => {@@ -120,33 +133,87 @@ fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut}HistSource::Channel { .. } => {}}- let img = photocraft_compose::thumbnail(&d, 384);+ let longest = d.size.width.max(d.size.height);+ let k = longest / 768;+ let (d, level) = if k >= 2 && d.size.area() > photocraft_compose::PROXY_THUMBNAIL_PIXELS && photocraft_compose::proxy::proxy_faithful(&d) {+ (photocraft_compose::proxy::proxy_document(&d, k), k.next_power_of_two().ilog2() + 1)+ } else {+ (d, 1)+ };+ let _ = photocraft_compose::render_bands(&d, d.bounds(), 0, |band| -> Result<(), ()> {+ #[cfg(not(target_arch = "wasm32"))]+ let part = {+ use rayon::prelude::*;+ band.px+ .par_chunks(64 * 1024)+ .map(|px| {+ let mut part = vec![[0u32; 256]; h.len()];+ count_pixels(px, space, &mut part);+ part+ })+ .reduce(|| vec![[0u32; 256]; h.len()], add_bins)+ };+ #[cfg(target_arch = "wasm32")]+ let part = {+ let mut part = vec![[0u32; 256]; h.len()];+ count_pixels(&band.px, space, &mut part);+ part+ };+ for (dst, src) in h.iter_mut().zip(&part) {+ for (a, b) in dst.iter_mut().zip(src) {+ *a = a.saturating_add(*b);+ }+ }+ Ok(())+ });+ level+}++/// Bin-wise sum of two sets of histograms (saturating: a hostile canvas can exceed `u32`).+#[cfg(not(target_arch = "wasm32"))]+fn add_bins(mut a: Vec<[u32; 256]>, b: Vec<[u32; 256]>) -> Vec<[u32; 256]> {+ for (dst, src) in a.iter_mut().zip(&b) {+ for (x, y) in dst.iter_mut().zip(src) {+ *x = x.saturating_add(*y);+ }+ }+ a+}++/// Counts straight-alpha composite pixels into `h` (one histogram per channel of `space`);+/// transparent pixels are skipped.+fn count_pixels(px: &[[f32; 4]], space: ToneSpace, h: &mut [[u32; 256]]) {let bin = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize;- for p in img.pixels.as_chunks::<4>().0 {- if p[3] == 0 {+ let mut add = |c: usize, b: usize| {+ if let Some(n) = h.get_mut(c).and_then(|ch| ch.get_mut(b)) {+ *n = n.saturating_add(1);+ }+ };+ for p in px {+ // Skips NaN alpha too.+ if p[3].is_nan() || p[3] <= 0.0 {continue;}match space {ToneSpace::Rgb => {- for c in 0..3 {- h[c + 1][p[c] as usize] += 1;+ let q = [p[0], p[1], p[2]].map(bin);+ for (c, v) in q.iter().enumerate() {+ add(c + 1, *v);}- h[0][((p[0] as u32 + p[1] as u32 + p[2] as u32) / 3) as usize] += 1;+ add(0, (q[0] + q[1] + q[2]) / 3);}ToneSpace::Cmyk => {- let rgb = [p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0);- let ink = photocraft_color::convert::rgb_to_cmyk(rgb);+ let ink = photocraft_color::convert::rgb_to_cmyk([p[0], p[1], p[2]].map(|v| v.clamp(0.0, 1.0)));for (c, v) in ink.iter().enumerate() {- h[c + 1][bin(1.0 - v)] += 1;+ add(c + 1, bin(1.0 - v));}- h[0][bin(1.0 - ink.iter().sum::<f32>() / 4.0)] += 1;+ add(0, bin(1.0 - ink.iter().sum::<f32>() / 4.0));}ToneSpace::Lab => {- let rgb = [p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0);- let l = photocraft_color::convert::srgb_to_lab(rgb);- h[0][bin(l[0] / 100.0)] += 1;- h[1][bin((l[1] + 128.0) / 255.0)] += 1;- h[2][bin((l[2] + 128.0) / 255.0)] += 1;+ let l = photocraft_color::convert::srgb_to_lab([p[0], p[1], p[2]].map(|v| v.clamp(0.0, 1.0)));+ add(0, bin(l[0] / 100.0));+ add(1, bin((l[1] + 128.0) / 255.0));+ add(2, bin((l[2] + 128.0) / 255.0));}}}@@ -351,9 +418,8 @@ pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {}}let Some((_, _, _, h)) = app.doc_hist.clone() else { return };- let size = app.session.active().map_or(photocraft_doc::Size::new(0, 0), |s| s.doc.size);- // Statistics come from a downsampled cache (like Photoshop's cache levels).- let level = (size.width.max(size.height) as f32 / 384.0).max(1.0).log2().ceil() as u32 + 1;+ // 1 when the statistics count every pixel; higher when a downsampled proxy stood in.+ let level = h.level.max(1);let ch = channel_picker(ui, egui::Id::new("histogram-panel-ch"), "Channel:");let w = ui.available_width();let (r, _) = ui.allocate_exact_size(vec2(w, 100.0), Sense::hover());@@ -383,7 +449,7 @@ pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {(tl!("Mean:"), format!("{mean:.2}")),(tl!("Std Dev:"), format!("{:.2}", var.sqrt())),(tl!("Median:"), median.unwrap_or(0).to_string()),- (tl!("Pixels:"), (size.width as u64 * size.height as u64).to_string()),+ (tl!("Pixels:"), n.to_string()),(tl!("Cache Level:"), level.to_string()),] {ui.label(egui::RichText::new(k).color(t.text_dim).size(11.5));@@ -486,6 +552,82 @@ mod tests {let tiny = (h[128] as f32 / top).min(1.0);assert!(tiny < 0.05, "tiny bin draws near-flat, got {tiny}");}++ /// A white document with black filled over columns `0..split` (a layer above the background).+ fn split_doc(w: u32, h: u32, split: u32, depth: Option<u32>) -> photocraft_engine::Session {+ let mut s = photocraft_engine::Session::new();+ let mut p = json!({"width": w, "height": h});+ if let Some(bits) = depth {+ p["depth"] = json!(bits);+ }+ s.execute("file.new", p).unwrap(); // white+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": split, "height": h})).unwrap();+ s.execute("edit.fill", json!({"color": "#000000"})).unwrap();+ s.execute("select.deselect", json!({})).unwrap();+ s+ }++ fn panel_histograms(s: &photocraft_engine::Session) -> Histograms {+ compute_histograms(&s.active().unwrap().doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb)+ }++ fn mean(h: &[u32; 256]) -> f64 {+ let n: u64 = h.iter().map(|v| u64::from(*v)).sum();+ h.iter().enumerate().map(|(i, v)| i as f64 * f64::from(*v)).sum::<f64>() / n as f64+ }++ /// #6538: a black/white split counts only black and white, wherever the edge falls (the old+ /// 384 px area-averaged thumbnail turned the cell holding the edge mid-grey), and counts+ /// every pixel: cache level 1.+ #[test]+ fn split_image_histogram_counts_only_black_and_white() {+ for (w, h, split) in [(1000, 1000, 334), (1000, 1000, 500), (1000, 600, 1), (777, 333, 389), (2000, 50, 1999), (64, 64, 32)] {+ let s = split_doc(w, h, split, None);+ let hist = panel_histograms(&s);+ assert_eq!(hist.level, 1, "{w}x{h}: every pixel is counted");+ for c in 0..4 {+ let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect();+ assert!(stray.is_empty(), "{w}x{h} split {split}, channel {c}: invented values {stray:?}");+ assert_eq!(u64::from(hist[c][0]), u64::from(split) * u64::from(h), "{w}x{h} split {split}: black pixels");+ assert_eq!(u64::from(hist[c][255]), u64::from(w - split) * u64::from(h), "{w}x{h} split {split}: white pixels");+ }+ }+ let half = panel_histograms(&split_doc(1000, 1000, 500, None));+ assert!((mean(&half[0]) - 127.5).abs() < 1e-9, "a 50/50 split has mean 127.5, got {}", mean(&half[0]));+ }++ /// The same at 16 and 32 bits per channel: the count does not go through an 8-bit thumbnail.+ #[test]+ fn split_image_histogram_is_exact_at_high_bit_depths() {+ for bits in [16, 32] {+ let s = split_doc(1000, 400, 334, Some(bits));+ assert_eq!(s.active().unwrap().doc.depth.bits(), bits, "the document is {bits}-bit");+ let hist = panel_histograms(&s);+ for c in 0..4 {+ let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect();+ assert!(stray.is_empty(), "{bits}-bit channel {c}: invented values {stray:?}");+ assert_eq!(hist[c][0], 334 * 400);+ assert_eq!(hist[c][255], 666 * 400);+ }+ }+ }++ /// Above the exact-count size a nearest-neighbour proxy stands in (cache level > 1): it is+ /// smaller, yet still only holds black and white.+ #[test]+ fn large_split_image_counts_a_nearest_proxy_without_inventing_greys() {+ let s = split_doc(6000, 3000, 2001, None);+ let hist = panel_histograms(&s);+ assert!(hist.level > 1, "a proxy stood in, level {}", hist.level);+ let n: u64 = hist[0].iter().map(|v| u64::from(*v)).sum();+ assert!(n > 0 && n < 6000 * 3000, "counted {n} proxy pixels");+ for c in 0..4 {+ let stray: Vec<(usize, u32)> = hist[c].iter().copied().enumerate().filter(|&(i, v)| v > 0 && i != 0 && i != 255).collect();+ assert!(stray.is_empty(), "channel {c}: invented values {stray:?}");+ }+ assert!((mean(&hist[0]) - 255.0 * 3999.0 / 6000.0).abs() < 1.0, "mean {}", mean(&hist[0]));+ }}#[cfg(test)]