mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-24 19:33:39 +01:00
LR-REM-HEAL: process V8 pins Heal to the spot's edge in log space, matches the grain, reads sources at whole pixels
Heal (and Remove's heal) added a Gaussian-weighted average of the difference between photo and source around the spot, in linear light. It was not pinned to the photo at the spot's edge: spots on gradients left a faint disc, dark features near a spot that it doesn't touch smudged in, texture moved across light kept its absolute amplitude (blotchy in shadows, flat in highlights), and bilinear reads at fractional source offsets halved the grain. Process V8 (docs/process-versions.md), so edited photos keep their look until Update to Current Process: - the patch is source * e^P, P the membrane fill (inpaint::membrane_fill) of the log ratio of photo to source, known only on the ring of pixels touching the spot, blurred there over the outside only (1.5 px); - the source's fine detail is scaled to the detail around the spot (ratio of medians, within 0.5 to 2x); - every spot, Clone included, reads its source at whole pixels; - the GPU renderer reads the image back for the spot stage on V8 photos with spots; V1 to V7 keep the device kernels. New tests in spots::pinned each also check that the previous heal fails them; existing spot tests run on both methods; GPU spots_match covers V7 and V8.
This commit is contained in:
1 parent
e9c29e2c5c
commit
a51aedcd2d
13 files changed
+545
-59
No files matched your search
@@ -99,12 +99,17 @@ pub enum Process {
|
||||
/// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution
|
||||
/// independent, fading out at black and white; V1 to V6 keep their value noise.
|
||||
V7,
|
||||
/// V7, with Heal and Remove spots pinned to the photo on the spot's edge: the correction is a
|
||||
/// membrane fill of the log ratio of photo to source, the source's fine detail is matched to its
|
||||
/// surroundings, and every spot reads its source at whole pixels
|
||||
/// (`lightcraft_pipeline::spots::HealMethod`).
|
||||
V8,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
/// Every process, oldest first.
|
||||
pub const ALL: [Process; 7] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7];
|
||||
pub const LATEST: Process = Process::V7;
|
||||
pub const ALL: [Process; 8] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8];
|
||||
pub const LATEST: Process = Process::V8;
|
||||
|
||||
pub const fn version(self) -> ProcessVersion {
|
||||
match self {
|
||||
@@ -115,6 +120,7 @@ impl Process {
|
||||
Process::V5 => ProcessVersion(5),
|
||||
Process::V6 => ProcessVersion(6),
|
||||
Process::V7 => ProcessVersion(7),
|
||||
Process::V8 => ProcessVersion(8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1070,6 +1070,14 @@ fn defringe(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
|
||||
fn spots(cx: &mut Cx<'_>, img: Buf, plan: &Plan<'_>) -> Buf {
|
||||
use lightcraft_pipeline::spots;
|
||||
let (w, h) = (plan.w, plan.h);
|
||||
let method = spots::HealMethod::of(&plan.settings);
|
||||
if method == spots::HealMethod::Pinned && !plan.settings.spots.is_empty() {
|
||||
// process V8's heal (a membrane solve per spot) has no kernel yet: the spots run on the CPU
|
||||
// between the device stages, the rest of the render stays on the device
|
||||
let mut host = cx.read_rgb(&img, w, h);
|
||||
spots::apply(&mut host, &plan.settings.spots, &plan.frame, plan.px_per_long, method);
|
||||
return cx.gpu.upload(rgb_words(&host));
|
||||
}
|
||||
for spot in &plan.settings.spots {
|
||||
let Some(l) = spots::layout(spot, &plan.frame, w, h, plan.px_per_long) else { continue };
|
||||
let Some(&first) = l.pts.first() else { continue };
|
||||
|
||||
@@ -1422,13 +1422,14 @@ fn soft_proofs_match() {
|
||||
|
||||
/// Spot removal on the device: Clone, Heal and Remove (automatic source, scored on the device),
|
||||
/// brushed strokes, overlapping spots (each reads what the earlier ones left), feather 0 and
|
||||
/// spots cut by the image edge.
|
||||
/// spots cut by the image edge; on process V7 by the device kernels, on V8 (the pinned heal) on the
|
||||
/// CPU between the device stages.
|
||||
#[test]
|
||||
fn spots_match() {
|
||||
if !gpu() {
|
||||
return;
|
||||
}
|
||||
use lightcraft_develop::SpotMode;
|
||||
use lightcraft_develop::{Process, SpotMode};
|
||||
let src = scene(3, 900, 600);
|
||||
let raw = SourceInfo { raw: true, ..Default::default() };
|
||||
let spot = |mode, pts: &[(f64, f64)], size, feather, off: Option<(f64, f64)>| Spot {
|
||||
@@ -1456,11 +1457,11 @@ fn spots_match() {
|
||||
],
|
||||
),
|
||||
];
|
||||
for (name, spots) in sets {
|
||||
let mut s = DevelopSettings::default();
|
||||
for ((name, spots), process) in sets.into_iter().flat_map(|set| [Process::V7, Process::V8].map(|p| (set.clone(), p))) {
|
||||
let mut s = DevelopSettings { process: process.version(), ..Default::default() };
|
||||
typical(&mut s);
|
||||
s.spots = spots;
|
||||
check(&format!("spots: {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640));
|
||||
check(&format!("spots ({process:?}): {name}"), &src, &raw, &s, &RenderRequest::fit(640, 640));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -148,8 +148,8 @@ impl GrainModel {
|
||||
seed: g.seed,
|
||||
})
|
||||
}),
|
||||
Process::V7 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal),
|
||||
Process::V7 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal),
|
||||
Process::V7 | Process::V8 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal),
|
||||
Process::V7 | Process::V8 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -407,7 +407,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
|
||||
},
|
||||
// V4, with a raw's tone curve rolling off into white in stops: a camera curve past its last
|
||||
// knot, the generic curve from half a stop below its white point instead of clipping (issue #1632)
|
||||
Process::V5 | Process::V6 | Process::V7 => match info.camera_tone.as_ref().filter(|_| info.raw) {
|
||||
Process::V5 | Process::V6 | Process::V7 | Process::V8 => match info.camera_tone.as_ref().filter(|_| info.raw) {
|
||||
Some(curve) => ToneMap::camera_rolloff_hdr(curve, 0.0, l.whites, 0.0, peak),
|
||||
None if info.raw => ToneMap::rolloff_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak),
|
||||
|
||||
@@ -516,6 +516,8 @@ pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &R
|
||||
geo,
|
||||
[wb_t, wb_tint, info.as_shot_temp, info.as_shot_tint].map(f64::to_bits),
|
||||
format!("{:?}", s.spots),
|
||||
// the process picks how spots heal (Update to Current Process, undo)
|
||||
(!s.spots.is_empty()).then(|| spots::HealMethod::of(s)),
|
||||
format!("{eyes:?}"),
|
||||
// defringe runs in this stage
|
||||
format!("{:?}", s.optics),
|
||||
@@ -616,7 +618,7 @@ pub fn lin_cpu(img: &mut Rgb32f, info: &SourceInfo, p: &Plan<'_>) {
|
||||
local_tone::apply(img, info, p);
|
||||
local::white_balance(img, info, s);
|
||||
optics::defringe(img, s, p.px_per_long / optics::DEFRINGE_REF_LONG);
|
||||
spots::apply(img, &s.spots, &p.frame, p.px_per_long);
|
||||
spots::apply(img, &s.spots, &p.frame, p.px_per_long, spots::HealMethod::of(s));
|
||||
redeye::apply(img, &p.eyes);
|
||||
}
|
||||
|
||||
|
||||
@@ -284,7 +284,7 @@ pub fn applies(s: &DevelopSettings, info: &SourceInfo) -> bool {
|
||||
let camera_look = info.raw && info.camera_tone.is_some();
|
||||
match s.process.process() {
|
||||
Process::V1 | Process::V2 | Process::V3 => false,
|
||||
Process::V4 | Process::V5 | Process::V6 | Process::V7 => camera_look,
|
||||
Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => camera_look,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize {
|
||||
pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize {
|
||||
match s.process.process() {
|
||||
Process::V1 => 0,
|
||||
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 => base_detail_radius(px_per_long),
|
||||
Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 | Process::V7 | Process::V8 => base_detail_radius(px_per_long),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
//! Remove / Heal / Clone spots, rendered at output resolution in scene-linear light.
|
||||
//!
|
||||
//! - **Clone** copies the source patch with a feathered edge.
|
||||
//! - **Heal** copies the source's *detail* and keeps the target's *tone*: result = src + blur(target − src)
|
||||
//! (frequency separation — a fast, stable approximation of gradient-domain healing).
|
||||
//! - **Heal** copies the source's *detail* and keeps the target's *tone*. How depends on the photo's
|
||||
//! process ([`HealMethod`]): from V8 the patch is pinned to the photo on the spot's edge by a membrane
|
||||
//! fill of the log ratio, with the source's fine detail matched to its surroundings ([`pinned`]);
|
||||
//! before V8 it is src + blur(target − src), a Gaussian-weighted average of the difference around the
|
||||
//! spot (frequency separation).
|
||||
//! - **Remove** is Heal with an automatically chosen source: candidate offsets on rings around the
|
||||
//! spot are scored by how well the source's surrounding annulus matches the target's.
|
||||
//! - **Fill** (content-aware) rebuilds the spot from patches of its surroundings instead of one
|
||||
@@ -10,12 +13,35 @@
|
||||
//! structure is chosen at a scale set by the spot's size (the same at preview and export size).
|
||||
//! Deterministic; the source offset is ignored.
|
||||
|
||||
use lightcraft_develop::{Spot, SpotMode};
|
||||
use lightcraft_develop::{DevelopSettings, Process, Spot, SpotMode};
|
||||
use lightcraft_geom::Point;
|
||||
use lightcraft_raster::Rgb32f;
|
||||
|
||||
use crate::geometry::Frame;
|
||||
|
||||
mod pinned;
|
||||
|
||||
/// How Heal and Remove spots blend their source in, and how every spot reads it: chosen by the
|
||||
/// photo's process (`docs/process-versions.md`), so a photo keeps its look until it is updated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum HealMethod {
|
||||
/// V1 to V7: the source plus a Gaussian-weighted average of the difference around the spot
|
||||
/// (not pinned to the spot's edge, added in linear light), the source read where its offset
|
||||
/// lands, between pixels.
|
||||
Averaged,
|
||||
/// V8 on: pinned to the photo on the spot's edge in log space, the source's fine detail matched
|
||||
/// to its surroundings ([`pinned`]), and every spot (Clone too) reads its source at whole pixels,
|
||||
/// so the grain isn't averaged away.
|
||||
Pinned,
|
||||
}
|
||||
|
||||
impl HealMethod {
|
||||
/// The method `s`'s process renders spots with.
|
||||
pub fn of(s: &DevelopSettings) -> HealMethod {
|
||||
if s.process.process() >= Process::V8 { HealMethod::Pinned } else { HealMethod::Averaged }
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
// Zero feather is a hard edge, including when the pixel lies exactly on the radius.
|
||||
@@ -383,17 +409,22 @@ fn fill_box(src: &mut [[f32; 3]], tgt: &[[f32; 3]], alpha: &[f32], bw: usize, bh
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply all spots to `img` (output resolution). `ppl` = output pixels per long-edge unit.
|
||||
pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) {
|
||||
/// Apply all spots to `img` (output resolution). `ppl` = output pixels per long-edge unit; `method`
|
||||
/// is [`HealMethod::of`] the photo's settings.
|
||||
pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64, method: HealMethod) {
|
||||
let (w, h) = (img.width, img.height);
|
||||
let pinned = method == HealMethod::Pinned;
|
||||
for spot in spots {
|
||||
let Some(SpotLayout { r, pts, offset, bx: bx0, by: by0, bw, bh, inner, opacity, heal, fill }) = layout(spot, frame, w, h, ppl) else {
|
||||
continue;
|
||||
};
|
||||
let Some(&first) = pts.first() else { continue };
|
||||
let offset = offset.unwrap_or_else(|| auto_source(img, first, r));
|
||||
// alpha of the stroke and source patch in the box
|
||||
// (V8 reads whole pixels: between them, bilinear sampling averages the source's grain away)
|
||||
let offset = if pinned { (offset.0.round(), offset.1.round()) } else { offset };
|
||||
// alpha of the stroke, its distance and the source patch in the box
|
||||
let mut alpha = vec![0.0f32; bw * bh];
|
||||
let mut dist = vec![0.0f32; bw * bh];
|
||||
let mut src = vec![[0.0f32; 3]; bw * bh];
|
||||
let mut tgt = vec![[0.0f32; 3]; bw * bh];
|
||||
for y in 0..bh {
|
||||
@@ -401,6 +432,7 @@ pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) {
|
||||
let (px, py) = ((bx0 + x) as f32 + 0.5, (by0 + y) as f32 + 0.5);
|
||||
let d = pts.iter().map(|p| ((px - p.0).powi(2) + (py - p.1).powi(2)).sqrt()).fold(f32::MAX, f32::min);
|
||||
alpha[y * bw + x] = (1.0 - smooth(inner, r, d)) * opacity;
|
||||
dist[y * bw + x] = d;
|
||||
src[y * bw + x] = img.sample_bilinear(px + offset.0, py + offset.1);
|
||||
tgt[y * bw + x] = img.get(bx0 + x, by0 + y);
|
||||
}
|
||||
@@ -408,7 +440,10 @@ pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) {
|
||||
if fill {
|
||||
fill_box(&mut src, &tgt, &alpha, bw, bh);
|
||||
}
|
||||
let low = if heal {
|
||||
if heal && pinned {
|
||||
src = pinned::heal(&pinned::Patch { w: bw, h: bh, src: &src, tgt: &tgt, dist: &dist, r });
|
||||
}
|
||||
let low = if heal && !pinned {
|
||||
// Tone correction from the spot's *surroundings* only: normalized convolution of
|
||||
// (target − source) over pixels outside the stroke (a membrane-like interpolation).
|
||||
let outside: Vec<f32> = alpha.iter().map(|a| if *a < 0.02 { 1.0 } else { 0.0 }).collect();
|
||||
@@ -458,11 +493,13 @@ pub fn apply(img: &mut Rgb32f, spots: &[Spot], frame: &Frame, ppl: f64) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use lightcraft_develop::DevelopSettings;
|
||||
|
||||
/// Both processes' spot rendering (before and from V8).
|
||||
const BOTH: [HealMethod; 2] = [HealMethod::Averaged, HealMethod::Pinned];
|
||||
|
||||
#[test]
|
||||
fn hard_edge_spots_at_zero_opacity_leave_every_pixel_unchanged() {
|
||||
for mode in [SpotMode::Clone, SpotMode::Heal, SpotMode::Remove, SpotMode::Fill] {
|
||||
for (mode, method) in [SpotMode::Clone, SpotMode::Heal, SpotMode::Remove, SpotMode::Fill].into_iter().flat_map(|m| BOTH.map(|h| (m, h))) {
|
||||
for (cx, cy) in [(32.5, 24.5), (0.5, 0.5)] {
|
||||
let original = Rgb32f::from_fn(64, 48, |x, y| [0.2 + x as f32 / 128.0, 0.3 + y as f32 / 128.0, 0.4]);
|
||||
let mut img = original.clone();
|
||||
@@ -475,9 +512,9 @@ mod tests {
|
||||
opacity: 0.0,
|
||||
source_offset: Some(Point::new(8.0 / 64.0, 0.0)),
|
||||
};
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(64));
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(64), method);
|
||||
for (i, (actual, expected)) in img.data.iter().zip(&original.data).enumerate() {
|
||||
assert_eq!(actual, expected, "zero-opacity {mode:?} at ({cx}, {cy}), pixel {i}");
|
||||
assert_eq!(actual, expected, "zero-opacity {mode:?} ({method:?}) at ({cx}, {cy}), pixel {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -485,7 +522,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hard_edge_clone_copies_inside_and_preserves_pixels_on_the_radius() {
|
||||
for (w, h, cx, cy, radius) in [(64, 48, 32.5, 24.5, 5.0), (128, 96, 64.5, 48.5, 10.0)] {
|
||||
for ((w, h, cx, cy, radius), method) in
|
||||
[(64, 48, 32.5, 24.5, 5.0), (128, 96, 64.5, 48.5, 10.0)].into_iter().flat_map(|c| BOTH.map(|m| (c, m)))
|
||||
{
|
||||
let original = Rgb32f::from_fn(w, h, |x, y| [0.2 + x as f32 / w as f32, y as f32 / h as f32, 0.4]);
|
||||
let mut img = original.clone();
|
||||
let frame = Frame::new(w, h, &DevelopSettings::default(), true);
|
||||
@@ -497,7 +536,7 @@ mod tests {
|
||||
opacity: 100.0,
|
||||
source_offset: Some(Point::new(0.125, 0.0)),
|
||||
};
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(w));
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(w), method);
|
||||
let (x, y) = (cx as usize, cy as usize);
|
||||
assert_eq!(img.get(x, y), original.get(x + w / 8, y), "inside copies the source at {w}px");
|
||||
assert_eq!(img.get(x + radius as usize, y), original.get(x + radius as usize, y), "radius stays unchanged at {w}px");
|
||||
@@ -507,18 +546,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn remove_erases_a_dot() {
|
||||
// flat grey with a gentle gradient and a black dot in the middle
|
||||
let mut img = Rgb32f::from_fn(120, 80, |x, _| [0.2 + x as f32 * 0.001; 3]);
|
||||
for y in 36..44 {
|
||||
for x in 56..64 {
|
||||
img.set(x, y, [0.0; 3]);
|
||||
for method in BOTH {
|
||||
// flat grey with a gentle gradient and a black dot in the middle
|
||||
let mut img = Rgb32f::from_fn(120, 80, |x, _| [0.2 + x as f32 * 0.001; 3]);
|
||||
for y in 36..44 {
|
||||
for x in 56..64 {
|
||||
img.set(x, y, [0.0; 3]);
|
||||
}
|
||||
}
|
||||
let frame = Frame::new(120, 80, &DevelopSettings::default(), true);
|
||||
let spot = Spot { points: vec![Point::new(0.5, 0.5)], size: 8.0 / 120.0, feather: 30.0, ..Default::default() };
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(120), method);
|
||||
let c = img.get(60, 40);
|
||||
assert!((c[0] - 0.26).abs() < 0.03, "{method:?}: {c:?}");
|
||||
}
|
||||
let frame = Frame::new(120, 80, &DevelopSettings::default(), true);
|
||||
let spot = Spot { points: vec![Point::new(0.5, 0.5)], size: 8.0 / 120.0, feather: 30.0, ..Default::default() };
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(120));
|
||||
let c = img.get(60, 40);
|
||||
assert!((c[0] - 0.26).abs() < 0.03, "{c:?}");
|
||||
}
|
||||
|
||||
/// Vertical stripes (period `period` px) with a black blot over the middle.
|
||||
@@ -552,7 +593,7 @@ mod tests {
|
||||
let (w, h) = (200, 160);
|
||||
let mut img = striped_with_blot(w, h, 8);
|
||||
let frame = Frame::new(w, h, &DevelopSettings::default(), true);
|
||||
apply(&mut img, &[fill_spot()], &frame, frame.px_per_long(w));
|
||||
apply(&mut img, &[fill_spot()], &frame, frame.px_per_long(w), HealMethod::Pinned);
|
||||
// the blot is gone and the stripes continue through it
|
||||
let mut err = 0.0f32;
|
||||
for x in 90..110 {
|
||||
@@ -561,7 +602,7 @@ mod tests {
|
||||
}
|
||||
assert!(err / 20.0 < 0.12, "mean error {}", err / 20.0);
|
||||
let mut again = striped_with_blot(w, h, 8);
|
||||
apply(&mut again, &[fill_spot()], &frame, frame.px_per_long(w));
|
||||
apply(&mut again, &[fill_spot()], &frame, frame.px_per_long(w), HealMethod::Pinned);
|
||||
assert_eq!(img.data, again.data);
|
||||
}
|
||||
|
||||
@@ -570,8 +611,8 @@ mod tests {
|
||||
// the same photo at two sizes: the half-size fill matches the full-size one, downsampled
|
||||
let (mut big, mut small) = (striped_with_blot(320, 240, 16), striped_with_blot(160, 120, 8));
|
||||
let (fb, fs) = (Frame::new(320, 240, &DevelopSettings::default(), true), Frame::new(160, 120, &DevelopSettings::default(), true));
|
||||
apply(&mut big, &[fill_spot()], &fb, fb.px_per_long(320));
|
||||
apply(&mut small, &[fill_spot()], &fs, fs.px_per_long(160));
|
||||
apply(&mut big, &[fill_spot()], &fb, fb.px_per_long(320), HealMethod::Pinned);
|
||||
apply(&mut small, &[fill_spot()], &fs, fs.px_per_long(160), HealMethod::Pinned);
|
||||
let (mut err, mut n) = (0.0f32, 0);
|
||||
for y in 50..70 {
|
||||
for x in 70..90 {
|
||||
@@ -589,26 +630,28 @@ mod tests {
|
||||
for (p, size) in [((0.0, 0.0), 2.0), ((-5.0, 9.0), 0.1), ((0.5, 0.5), 0.0), ((f64::NAN, 0.5), 0.1), ((0.5, 0.5), f64::INFINITY)] {
|
||||
let mut img = Rgb32f::from_fn(40, 30, |x, _| [x as f32 / 40.0; 3]);
|
||||
let spot = Spot { mode: SpotMode::Fill, points: vec![Point::new(p.0, p.1)], size, ..Default::default() };
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(40));
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(40), HealMethod::Pinned);
|
||||
assert!(img.data.iter().flatten().all(|v| v.is_finite()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clone_copies_source() {
|
||||
let mut img = Rgb32f::from_fn(100, 100, |x, _| if x < 50 { [0.1; 3] } else { [0.9; 3] });
|
||||
let frame = Frame::new(100, 100, &DevelopSettings::default(), true);
|
||||
let spot = Spot {
|
||||
mode: SpotMode::Clone,
|
||||
points: vec![Point::new(0.25, 0.5)],
|
||||
size: 0.05,
|
||||
feather: 0.0,
|
||||
source_offset: Some(Point::new(0.5, 0.0)),
|
||||
..Default::default()
|
||||
};
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(100));
|
||||
assert!(img.get(25, 50)[0] > 0.8);
|
||||
assert!(img.get(5, 50)[0] < 0.2);
|
||||
for method in BOTH {
|
||||
let mut img = Rgb32f::from_fn(100, 100, |x, _| if x < 50 { [0.1; 3] } else { [0.9; 3] });
|
||||
let frame = Frame::new(100, 100, &DevelopSettings::default(), true);
|
||||
let spot = Spot {
|
||||
mode: SpotMode::Clone,
|
||||
points: vec![Point::new(0.25, 0.5)],
|
||||
size: 0.05,
|
||||
feather: 0.0,
|
||||
source_offset: Some(Point::new(0.5, 0.0)),
|
||||
..Default::default()
|
||||
};
|
||||
apply(&mut img, &[spot], &frame, frame.px_per_long(100), method);
|
||||
assert!(img.get(25, 50)[0] > 0.8, "{method:?}");
|
||||
assert!(img.get(5, 50)[0] < 0.2, "{method:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn with_spots(spots: Vec<Spot>) -> DevelopSettings {
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
//! Process V8's heal (Heal spots, and Remove spots with their automatic source): the source keeps its
|
||||
//! detail, and a smooth correction pins the patch to the photo on the spot's edge.
|
||||
//!
|
||||
//! The patch is `g · e^P` in log space, `g` the source: `P` solves Laplace's equation inside the spot,
|
||||
//! with the log ratio of photo to source on the pixels just outside it as Dirichlet values. This is
|
||||
//! the healing of T. Georgiev, *Photoshop Healing Brush: a Tool for Seamless Cloning* (ECCV 2004
|
||||
//! workshop): the difference of photo and source, filled from its values on the boundary, added back
|
||||
//! to the source; that is the membrane interpolant of P. Pérez, M. Gangnet, A. Blake, *Poisson Image
|
||||
//! Editing* (SIGGRAPH 2003). Taking the ratio rather than the difference carries the source's texture
|
||||
//! at its contrast relative to the new light instead of at its absolute amplitude (the relighting-
|
||||
//! invariant form of T. Georgiev, *Image Reconstruction Invariant to Relighting*, Eurographics 2005).
|
||||
//!
|
||||
//! Two adjustments for photographs:
|
||||
//! * the source's finest detail, mostly sensor noise (relatively stronger in shadows, so a ratio
|
||||
//! alone carries too little of it into a darker spot), is scaled to the level around the spot,
|
||||
//! measured with medians so that edges don't count;
|
||||
//! * the edge values are a light blur of the outside, so that the noise of one ring of pixels doesn't
|
||||
//! ripple through the fill.
|
||||
//!
|
||||
//! The fill is `lightcraft_inpaint::membrane_fill` (cascadic SOR). See `docs/process-versions.md` (V8).
|
||||
|
||||
use lightcraft_color::luminance_2020;
|
||||
use lightcraft_raster::Plane;
|
||||
use lightcraft_raster::blur::gaussian;
|
||||
|
||||
/// Added before taking logs (scene-linear, diffuse white near 1): keeps black finite and makes the
|
||||
/// heal additive rather than multiplicative far below it.
|
||||
const LOG_FLOOR: f32 = 1.0 / 4096.0;
|
||||
/// Fine detail is what a Gaussian blur of this many pixels removes; the edge values are blurred by
|
||||
/// as much.
|
||||
const DETAIL_SIGMA: f32 = 1.5;
|
||||
/// The most the source's detail is weakened or strengthened.
|
||||
const GAIN_RANGE: (f32, f32) = (0.5, 2.0);
|
||||
/// Fewest pixels a detail level is measured on; with fewer, the source's detail is kept as it is.
|
||||
const MIN_SAMPLES: usize = 32;
|
||||
/// Where the detail around the spot is measured: this many radii from the stroke.
|
||||
const AROUND: (f32, f32) = (1.05, 2.0);
|
||||
/// Where the source's detail is measured: within this many radii of the stroke.
|
||||
const WITHIN: f32 = 0.9;
|
||||
|
||||
/// A spot's working box, row-major `w × h`: the source read for each pixel, the photo, and each
|
||||
/// pixel's distance to the stroke (output pixels); `r` is the spot's radius.
|
||||
pub(super) struct Patch<'a> {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub src: &'a [[f32; 3]],
|
||||
pub tgt: &'a [[f32; 3]],
|
||||
pub dist: &'a [f32],
|
||||
pub r: f32,
|
||||
}
|
||||
|
||||
fn enc(v: f32) -> f32 {
|
||||
(v.max(0.0) + LOG_FLOOR).ln()
|
||||
}
|
||||
|
||||
fn dec(v: f32) -> f32 {
|
||||
(v.exp() - LOG_FLOOR).max(0.0)
|
||||
}
|
||||
|
||||
/// The healed box: inside the spot (distance below `r`) the source with its detail matched, pinned to
|
||||
/// the photo at the spot's edge; outside it the photo. Inputs of mismatched sizes give the photo back.
|
||||
pub(super) fn heal(p: &Patch<'_>) -> Vec<[f32; 3]> {
|
||||
let n = p.w.saturating_mul(p.h);
|
||||
if p.src.len() != n || p.tgt.len() != n || p.dist.len() != n {
|
||||
return p.tgt.to_vec();
|
||||
}
|
||||
let cover: Vec<bool> = p.dist.iter().map(|d| *d < p.r).collect();
|
||||
let Some(sub) = SubBox::around(&cover, p.w, p.h) else { return p.tgt.to_vec() };
|
||||
let source = source_log(p, detail_gain(p, &cover));
|
||||
let edge = edge_ratio(p, &cover, &source);
|
||||
let fill = solve(p, &cover, &edge, &sub);
|
||||
let mut out = p.tgt.to_vec();
|
||||
for yy in 0..sub.h {
|
||||
for xx in 0..sub.w {
|
||||
let i = (sub.y + yy) * p.w + sub.x + xx;
|
||||
if !cover[i] {
|
||||
continue;
|
||||
}
|
||||
let j = (yy * sub.w + xx) * 3;
|
||||
let v: [f32; 3] = std::array::from_fn(|c| dec(source[c][i] + fill.get(j + c).copied().unwrap_or(0.0)));
|
||||
if v.iter().all(|c| c.is_finite()) {
|
||||
out[i] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// How much the source's fine detail is scaled so that it matches the photo's around the spot: the
|
||||
/// median absolute fine detail of log luminance there over the same inside the source, within
|
||||
/// [`GAIN_RANGE`]; 1 when either has too few pixels or no detail at all.
|
||||
fn detail_gain(p: &Patch<'_>, cover: &[bool]) -> f32 {
|
||||
let fine = |px: &[[f32; 3]]| {
|
||||
let l = Plane { width: p.w, height: p.h, data: px.iter().map(|c| enc(luminance_2020(*c))).collect() };
|
||||
let base = gaussian(&l, DETAIL_SIGMA);
|
||||
l.data.iter().zip(&base.data).map(|(v, b)| (v - b).abs()).collect::<Vec<f32>>()
|
||||
};
|
||||
let (ft, fs) = (fine(p.tgt), fine(p.src));
|
||||
let (lo, hi) = (AROUND.0 * p.r, AROUND.1 * p.r);
|
||||
let around: Vec<f32> = ft.iter().zip(p.dist).zip(cover).filter(|((_, d), c)| !**c && **d >= lo && **d < hi).map(|((v, _), _)| *v).collect();
|
||||
let within: Vec<f32> = fs.iter().zip(p.dist).filter(|(_, d)| **d < WITHIN * p.r).map(|(v, _)| *v).collect();
|
||||
match (median(around), median(within)) {
|
||||
(Some(t), Some(s)) if t > 0.0 && s > 0.0 => (t / s).clamp(GAIN_RANGE.0, GAIN_RANGE.1),
|
||||
_ => 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn median(mut v: Vec<f32>) -> Option<f32> {
|
||||
if v.len() < MIN_SAMPLES {
|
||||
return None;
|
||||
}
|
||||
let mid = v.len() / 2;
|
||||
let (_, m, _) = v.select_nth_unstable_by(mid, f32::total_cmp);
|
||||
Some(*m).filter(|m| m.is_finite())
|
||||
}
|
||||
|
||||
/// The source in log space, per channel, its fine detail scaled by `gain`.
|
||||
fn source_log(p: &Patch<'_>, gain: f32) -> [Vec<f32>; 3] {
|
||||
std::array::from_fn(|c| {
|
||||
let l = Plane { width: p.w, height: p.h, data: p.src.iter().map(|v| enc(v[c])).collect() };
|
||||
if (gain - 1.0).abs() < 1e-3 {
|
||||
return l.data;
|
||||
}
|
||||
let base = gaussian(&l, DETAIL_SIGMA);
|
||||
l.data.iter().zip(&base.data).map(|(v, b)| b + gain * (v - b)).collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// The log ratio of photo to source outside the spot, per channel, blurred over the outside only
|
||||
/// (normalized convolution), so that the ring the fill is pinned to carries no single pixel's noise.
|
||||
fn edge_ratio(p: &Patch<'_>, cover: &[bool], source: &[Vec<f32>; 3]) -> [Vec<f32>; 3] {
|
||||
let outside = Plane { width: p.w, height: p.h, data: cover.iter().map(|c| if *c { 0.0 } else { 1.0 }).collect() };
|
||||
let weight = gaussian(&outside, DETAIL_SIGMA);
|
||||
std::array::from_fn(|c| {
|
||||
let ratio = Plane {
|
||||
width: p.w,
|
||||
height: p.h,
|
||||
data: p.tgt.iter().zip(&source[c]).zip(cover).map(|((t, s), inside)| if *inside { 0.0 } else { enc(t[c]) - s }).collect(),
|
||||
};
|
||||
let blurred = gaussian(&ratio, DETAIL_SIGMA);
|
||||
blurred.data.iter().zip(&weight.data).map(|(v, m)| v / m.max(1e-4)).collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// The membrane fill of the edge ratio over `sub` (interleaved, 3 channels): the pixels next to the
|
||||
/// spot (4-neighbours of it) are the only known values, so nothing farther out leaks in through the
|
||||
/// solver's coarse levels.
|
||||
fn solve(p: &Patch<'_>, cover: &[bool], edge: &[Vec<f32>; 3], sub: &SubBox) -> Vec<f32> {
|
||||
let mut field = vec![0.0f32; sub.w * sub.h * 3];
|
||||
let mut unknown = vec![true; sub.w * sub.h];
|
||||
for yy in 0..sub.h {
|
||||
for xx in 0..sub.w {
|
||||
let (x, y) = (sub.x + xx, sub.y + yy);
|
||||
if cover[y * p.w + x] || !touches(cover, p.w, p.h, x, y) {
|
||||
continue;
|
||||
}
|
||||
let j = yy * sub.w + xx;
|
||||
unknown[j] = false;
|
||||
for (c, e) in edge.iter().enumerate() {
|
||||
field[j * 3 + c] = e[y * p.w + x];
|
||||
}
|
||||
}
|
||||
}
|
||||
lightcraft_inpaint::membrane_fill(sub.w, sub.h, 3, &field, &unknown)
|
||||
}
|
||||
|
||||
/// Whether pixel (x, y) has a 4-neighbour inside the spot.
|
||||
fn touches(cover: &[bool], w: usize, h: usize, x: usize, y: usize) -> bool {
|
||||
let i = y * w + x;
|
||||
(x > 0 && cover[i - 1]) || (x + 1 < w && cover[i + 1]) || (y > 0 && cover[i - w]) || (y + 1 < h && cover[i + w])
|
||||
}
|
||||
|
||||
/// The part of the box the fill works in: the spot's bounding box and the ring around it.
|
||||
struct SubBox {
|
||||
x: usize,
|
||||
y: usize,
|
||||
w: usize,
|
||||
h: usize,
|
||||
}
|
||||
|
||||
impl SubBox {
|
||||
fn around(cover: &[bool], w: usize, h: usize) -> Option<SubBox> {
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0, 0);
|
||||
for (i, _) in cover.iter().enumerate().filter(|(_, c)| **c) {
|
||||
let (x, y) = (i % w, i / w);
|
||||
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
|
||||
}
|
||||
if x0 == usize::MAX {
|
||||
return None;
|
||||
}
|
||||
let (x, y) = (x0.saturating_sub(1), y0.saturating_sub(1));
|
||||
Some(SubBox { x, y, w: (x1 + 2).min(w) - x, h: (y1 + 2).min(h) - y })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::{HealMethod, apply};
|
||||
use crate::geometry::Frame;
|
||||
use lightcraft_develop::{DevelopSettings, Process, Spot, SpotMode};
|
||||
use lightcraft_geom::Point;
|
||||
use lightcraft_raster::Rgb32f;
|
||||
|
||||
const W: usize = 256;
|
||||
|
||||
fn grey(v: f32) -> [f32; 3] {
|
||||
[v; 3]
|
||||
}
|
||||
|
||||
/// Uniform noise in -1..1 from a pixel position (no RNG state: the same image every run).
|
||||
fn noise(x: usize, y: usize, seed: u32) -> f32 {
|
||||
let mut h = (x as u32).wrapping_mul(374_761_393) ^ (y as u32).wrapping_mul(668_265_263) ^ seed.wrapping_mul(2_246_822_519);
|
||||
h = (h ^ (h >> 13)).wrapping_mul(1_274_126_177);
|
||||
h ^= h >> 16;
|
||||
(f64::from(h) / f64::from(u32::MAX)) as f32 * 2.0 - 1.0
|
||||
}
|
||||
|
||||
fn dist(x: usize, y: usize, c: (f32, f32)) -> f32 {
|
||||
(x as f32 + 0.5 - c.0).hypot(y as f32 + 0.5 - c.1)
|
||||
}
|
||||
|
||||
/// A Heal spot of radius `r` px at `c` reading from `off` px away, hard-edged, on a square `W` image.
|
||||
fn heal_spot(c: (f32, f32), r: f32, off: (f32, f32)) -> Spot {
|
||||
let n = W as f64;
|
||||
Spot {
|
||||
mode: SpotMode::Heal,
|
||||
points: vec![Point::new(f64::from(c.0) / n, f64::from(c.1) / n)],
|
||||
size: f64::from(r) / n,
|
||||
feather: 0.0,
|
||||
opacity: 100.0,
|
||||
source_offset: Some(Point::new(f64::from(off.0) / n, f64::from(off.1) / n)),
|
||||
}
|
||||
}
|
||||
|
||||
fn healed(img: &Rgb32f, spot: Spot, method: HealMethod) -> Rgb32f {
|
||||
let mut out = img.clone();
|
||||
let frame = Frame::new(img.width, img.height, &DevelopSettings::default(), true);
|
||||
apply(&mut out, &[spot], &frame, frame.px_per_long(img.width), method);
|
||||
out
|
||||
}
|
||||
|
||||
/// Green values of `img` at distances `lo..hi` from `c`.
|
||||
fn ring(img: &Rgb32f, c: (f32, f32), lo: f32, hi: f32) -> Vec<f32> {
|
||||
(0..img.height)
|
||||
.flat_map(|y| (0..img.width).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| (lo..hi).contains(&dist(x, y, c)))
|
||||
.map(|(x, y)| img.get(x, y)[1])
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn mean_std(v: &[f32]) -> (f32, f32) {
|
||||
let m = v.iter().sum::<f32>() / v.len() as f32;
|
||||
(m, (v.iter().map(|x| (x - m).powi(2)).sum::<f32>() / v.len() as f32).sqrt())
|
||||
}
|
||||
|
||||
/// The largest difference between `a` and `b` at distances `lo..hi` from `c`.
|
||||
fn max_err(a: &Rgb32f, b: &Rgb32f, c: (f32, f32), lo: f32, hi: f32) -> f32 {
|
||||
ring(a, c, lo, hi).iter().zip(ring(b, c, lo, hi)).map(|(p, q)| (p - q).abs()).fold(0.0, f32::max)
|
||||
}
|
||||
|
||||
/// `img` with a disc of `v` (radius `r` px) at `c`.
|
||||
fn blot(mut img: Rgb32f, c: (f32, f32), r: f32, v: f32) -> Rgb32f {
|
||||
for y in 0..img.height {
|
||||
for x in 0..img.width {
|
||||
if dist(x, y, c) < r {
|
||||
img.set(x, y, grey(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_process_picks_the_heal() {
|
||||
let on = |p: Process| DevelopSettings { process: p.version(), ..Default::default() };
|
||||
assert_eq!(HealMethod::of(&on(Process::V7)), HealMethod::Averaged);
|
||||
assert_eq!(HealMethod::of(&on(Process::V8)), HealMethod::Pinned);
|
||||
assert_eq!(HealMethod::of(&DevelopSettings::default()), HealMethod::Pinned, "new photos get the latest process");
|
||||
}
|
||||
|
||||
// Given a spot on a brightness ramp and a source on a flat area, the healed patch meets the
|
||||
// ramp at the spot's edge (the averaged correction left a step of about 10 % there)
|
||||
#[test]
|
||||
fn a_heal_on_a_gradient_meets_it_at_the_edge() {
|
||||
let truth = Rgb32f::from_fn(W, W, |x, y| grey(if y < 100 { 0.3 } else { 0.3 + 0.004 * (x as f32 - 128.0) }));
|
||||
let (c, r) = ((128.0, 180.0), 20.0);
|
||||
let img = blot(truth.clone(), c, 0.7 * r, 0.02);
|
||||
let spot = heal_spot(c, r, (0.0, -130.0));
|
||||
let pinned = healed(&img, spot.clone(), HealMethod::Pinned);
|
||||
let averaged = healed(&img, spot, HealMethod::Averaged);
|
||||
let (edge_p, edge_a) = (max_err(&pinned, &truth, c, 0.8 * r, r), max_err(&averaged, &truth, c, 0.8 * r, r));
|
||||
assert!(edge_p < 0.006, "pinned edge error {edge_p}");
|
||||
assert!(edge_a > 0.02, "the averaged correction misses the edge ({edge_a}): the test would not catch a revert");
|
||||
assert!(max_err(&pinned, &truth, c, 0.0, r) < 0.01, "inside");
|
||||
}
|
||||
|
||||
// Given texture moved from a bright area into one 4 stops darker, the patch keeps the texture's
|
||||
// contrast relative to its new light (added in linear light, it was 7x too strong, a third clipped)
|
||||
#[test]
|
||||
fn a_heal_into_a_shadow_keeps_the_texture_contrast() {
|
||||
let truth = Rgb32f::from_fn(W, W, |x, y| grey(if x < 128 { 0.8 } else { 0.05 } * (1.0 + 0.25 * noise(x, y, 7))));
|
||||
let (c, r) = ((192.0, 128.0), 20.0);
|
||||
let img = blot(truth.clone(), c, 0.7 * r, 0.3);
|
||||
let spot = heal_spot(c, r, (-128.0, 0.0));
|
||||
let relative = |img: &Rgb32f| {
|
||||
let (m, s) = mean_std(&ring(img, c, 0.0, 0.8 * r));
|
||||
s / m
|
||||
};
|
||||
let want = relative(&truth);
|
||||
let (p, a) = (relative(&healed(&img, spot.clone(), HealMethod::Pinned)), relative(&healed(&img, spot, HealMethod::Averaged)));
|
||||
assert!((p / want - 1.0).abs() < 0.25, "pinned texture contrast {p}, the photo's {want}");
|
||||
assert!(a > 3.0 * want, "the averaged heal's contrast {a}: the test would not catch a revert");
|
||||
}
|
||||
|
||||
// Given a dark line just outside the spot that its edge doesn't touch, the patch stays as light
|
||||
// as its surroundings (the averaged correction pulled the line's darkness in)
|
||||
#[test]
|
||||
fn a_heal_ignores_what_does_not_touch_the_spot() {
|
||||
let (c, r) = ((128.0, 150.0), 20.0);
|
||||
let bar_x = (c.0 + 1.4 * r) as usize;
|
||||
let img = Rgb32f::from_fn(W, W, |x, y| {
|
||||
let bar = (bar_x..bar_x + 4).contains(&x) && (y as f32 - c.1).abs() < 1.5 * r;
|
||||
grey(if bar { 0.02 } else { 0.3 })
|
||||
});
|
||||
let spot = heal_spot(c, r, (0.0, -100.0));
|
||||
let darkest = |img: &Rgb32f| ring(img, c, 0.0, r).into_iter().fold(f32::MAX, f32::min);
|
||||
let (p, a) = (darkest(&healed(&img, spot.clone(), HealMethod::Pinned)), darkest(&healed(&img, spot, HealMethod::Averaged)));
|
||||
assert!(p > 0.297, "pinned: darkest {p}, the surroundings 0.3");
|
||||
assert!(a < 0.28, "the averaged heal's darkest {a}: the test would not catch a revert");
|
||||
}
|
||||
|
||||
// Given a source half a pixel off the grid, Heal and Clone keep the grain (bilinear reads
|
||||
// between pixels halved it)
|
||||
#[test]
|
||||
fn sources_are_read_at_whole_pixels() {
|
||||
let img = Rgb32f::from_fn(W, W, |x, y| grey(0.3 * (1.0 + 0.2 * noise(x, y, 3))));
|
||||
let (c, r) = ((128.0, 128.0), 20.0);
|
||||
let (_, grain) = mean_std(&ring(&img, c, 0.0, 0.8 * r));
|
||||
for mode in [SpotMode::Heal, SpotMode::Clone] {
|
||||
let spot = Spot { mode, ..heal_spot(c, r, (40.5, 0.5)) };
|
||||
let kept = |method| mean_std(&ring(&healed(&img, spot.clone(), method), c, 0.0, 0.8 * r)).1 / grain;
|
||||
let (p, a) = (kept(HealMethod::Pinned), kept(HealMethod::Averaged));
|
||||
assert!(p > 0.9, "{mode:?}: whole-pixel source keeps {p} of the grain");
|
||||
assert!(a < 0.6, "{mode:?}: between pixels {a}: the test would not catch a revert");
|
||||
}
|
||||
}
|
||||
|
||||
// Given a source less grainy than the area around the spot, the patch takes the grain of its
|
||||
// surroundings, not the source's
|
||||
#[test]
|
||||
fn a_heal_matches_the_grain_around_the_spot() {
|
||||
let img = Rgb32f::from_fn(W, W, |x, y| grey(0.3 * (1.0 + if x < 128 { 0.06 } else { 0.11 } * noise(x, y, 5))));
|
||||
let (c, r) = ((192.0, 128.0), 20.0);
|
||||
let spot = heal_spot(c, r, (-128.0, 0.0));
|
||||
let (_, around) = mean_std(&ring(&img, c, 1.2 * r, 2.0 * r));
|
||||
let grain = |method| mean_std(&ring(&healed(&img, spot.clone(), method), c, 0.0, 0.8 * r)).1 / around;
|
||||
let (p, a) = (grain(HealMethod::Pinned), grain(HealMethod::Averaged));
|
||||
assert!((0.85..1.2).contains(&p), "pinned: {p} of the surroundings' grain");
|
||||
assert!(a < 0.65, "the averaged heal keeps the source's grain ({a}): the test would not catch a revert");
|
||||
}
|
||||
|
||||
// Given the same scene rendered at two sizes, the half-size heal matches the full-size one,
|
||||
// downsampled (settings are resolution independent)
|
||||
#[test]
|
||||
fn a_heal_matches_between_preview_and_export_size() {
|
||||
let scene = |n: usize| {
|
||||
let k = n as f32 / W as f32;
|
||||
let img = Rgb32f::from_fn(n, n, |x, y| grey(0.2 + 0.0015 * x as f32 / k + 0.001 * y as f32 / k));
|
||||
blot(img, (128.0 * k, 150.0 * k), 12.0 * k, 0.05)
|
||||
};
|
||||
let spot = heal_spot((128.0, 150.0), 18.0, (-60.0, -40.0));
|
||||
let frame = |n: usize| Frame::new(n, n, &DevelopSettings::default(), true);
|
||||
let (mut big, mut small) = (scene(2 * W), scene(W));
|
||||
let (fb, fs) = (frame(2 * W), frame(W));
|
||||
apply(&mut big, std::slice::from_ref(&spot), &fb, fb.px_per_long(2 * W), HealMethod::Pinned);
|
||||
apply(&mut small, &[spot], &fs, fs.px_per_long(W), HealMethod::Pinned);
|
||||
let mut worst = 0.0f32;
|
||||
for y in 130..170 {
|
||||
for x in 108..148 {
|
||||
let b = [(0, 0), (1, 0), (0, 1), (1, 1)].iter().map(|(dx, dy)| big.get(2 * x + dx, 2 * y + dy)[1]).sum::<f32>() / 4.0;
|
||||
worst = worst.max((b - small.get(x, y)[1]).abs());
|
||||
}
|
||||
}
|
||||
assert!(worst < 0.01, "largest difference {worst}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_heal_is_deterministic() {
|
||||
let img = Rgb32f::from_fn(W, W, |x, y| grey(0.3 * (1.0 + 0.2 * noise(x, y, 9))));
|
||||
let spot = Spot { mode: SpotMode::Remove, source_offset: None, ..heal_spot((100.0, 120.0), 15.0, (0.0, 0.0)) };
|
||||
assert_eq!(healed(&img, spot.clone(), HealMethod::Pinned).data, healed(&img, spot, HealMethod::Pinned).data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_heal_spots_render_finite_pixels() {
|
||||
let img = Rgb32f::from_fn(40, 30, |x, y| if x < 5 { [0.0; 3] } else { [x as f32 / 40.0, y as f32 / 30.0, 0.0] });
|
||||
let frame = Frame::new(40, 30, &DevelopSettings::default(), true);
|
||||
let hostile = [
|
||||
((0.0, 0.0), 2.0, Some((0.1, 0.0))),
|
||||
((-5.0, 9.0), 0.1, None),
|
||||
((0.5, 0.5), 0.0, Some((f64::NAN, 0.0))),
|
||||
((f64::NAN, 0.5), 0.1, None),
|
||||
((0.5, 0.5), f64::INFINITY, Some((1e30, -1e30))),
|
||||
((0.05, 0.5), 0.2, Some((0.5, 0.0))),
|
||||
];
|
||||
for ((p, size, off), mode) in hostile.into_iter().flat_map(|h| [SpotMode::Heal, SpotMode::Remove, SpotMode::Clone].map(|m| (h, m))) {
|
||||
let mut out = img.clone();
|
||||
let spot =
|
||||
Spot { mode, points: vec![Point::new(p.0, p.1)], size, source_offset: off.map(|o| Point::new(o.0, o.1)), ..Default::default() };
|
||||
apply(&mut out, &[spot], &frame, frame.px_per_long(40), HealMethod::Pinned);
|
||||
assert!(out.data.iter().flatten().all(|v| v.is_finite() && *v >= 0.0), "{mode:?} at {p:?} size {size}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ fn processes_before_v7_keep_the_value_noise() {
|
||||
Process::V1 | Process::V2 | Process::V3 | Process::V4 | Process::V5 | Process::V6 => {
|
||||
assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}")
|
||||
}
|
||||
Process::V7 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"),
|
||||
Process::V7 | Process::V8 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"),
|
||||
}
|
||||
assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0");
|
||||
}
|
||||
|
||||
@@ -267,8 +267,8 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts).
|
||||
| Id | Feature | Tier | Status | Evidence | Missing / notes |
|
||||
|---|---|---|---|---|---|
|
||||
| LR-REM-CONTENTAWARE | Content-aware remove | P1 | 🟡 | `cmd:spot.add` (`mode: remove` / `fill`), `crates/pipeline/src/spots.rs`, `crates/inpaint/src/lib.rs` | Remove heals with an automatic source; Fill synthesises the area from its surroundings (PatchMatch completion over a membrane-blended start, `crates/inpaint`, ported from PhotoCraft; bounded by the spot size limit); no generative fill (M8.4) |
|
||||
| LR-REM-HEAL | Heal | P0 | ✅ | `cmd:spot.add` (`mode: heal`), `crates/pipeline/src/spots.rs` | Zero-feather edges use a hard step; zero-opacity spots preserve all pixels, including exact-radius pixels and image corners |
|
||||
| LR-REM-CLONE | Clone | P0 | ✅ | `cmd:spot.add` (`mode: clone`), `crates/pipeline/src/spots.rs` | Hard-edge source copying and unchanged radius pixels regression-tested at two output sizes |
|
||||
| LR-REM-HEAL | Heal | P0 | ✅ | `cmd:spot.add` (`mode: heal`), `crates/pipeline/src/spots.rs`, `crates/pipeline/src/spots/pinned.rs` | From process V8 the patch is pinned to the photo on the spot's edge (membrane fill of the log ratio of photo to source), carries texture at its contrast relative to the new light, takes the grain of its surroundings and reads its source at whole pixels; V1 to V7 keep the averaged correction. Zero-feather edges use a hard step; zero-opacity spots preserve all pixels, including exact-radius pixels and image corners |
|
||||
| LR-REM-CLONE | Clone | P0 | ✅ | `cmd:spot.add` (`mode: clone`), `crates/pipeline/src/spots.rs` | Hard-edge source copying and unchanged radius pixels regression-tested at two output sizes; from process V8 the source is read at whole pixels |
|
||||
| LR-REM-GEN | Generative remove | OOS | 🚫 | | |
|
||||
| LR-REM-DETECT | Object detection for remove | P2 | ⬜ | | |
|
||||
| LR-REM-BRUSH-PARAMS | Brush size / feather / opacity | P0 | ✅ | `cmd:spot.add` (`size`, `feather`, `opacity`), `cmd:brush.smaller`, `cmd:brush.larger`, `cmd:brush.featherLess`, `cmd:brush.featherMore`, `crates/ui-egui/src/panels/right.rs` | Size / Feather / Opacity sliders (for new spots and the selected one); `[` `]` size, ⇧`[` ⇧`]` feather (also the Masking brush) |
|
||||
@@ -732,7 +732,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06-
|
||||
| LRC-DEV-CALIB | Calibration panel | P1 | ✅ | `ctl:calibration.*` | |
|
||||
| LRC-DEV-TAT | Targeted adjustment tools | P1 | ✅ | `cmd:develop.targeted` (`target`: curve / hue / sat / lum) | |
|
||||
| LRC-DEV-DEFAULTS | Per-camera raw defaults | P1 | ✅ | `cmd:library.preferences` (`camera`, `import.perCamera`), `crates/ui-egui/src/dialogs/settings.rs` | Settings → Import: raw default and per-camera presets |
|
||||
| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. |
|
||||
| LRC-DEV-PROCESS | Process versions, Update to Current Process | P1 | ✅ | `cmd:develop.updateProcess`, `cmd:develop.reset`, `cmd:develop.get`, `crates/develop/src/settings.rs`, `crates/pipeline/src/finish.rs`, `docs/process-versions.md` | Each photo keeps its saved rendering process. V1 is legacy, V2 preserves Highlights/Shadows detail, V3 is pixel-scale sharpening, V4 calibrates camera-look Contrast and Blacks, V5 rolls raw tone curves off into white in stops (#1632), V6 takes colour noise reduction to the joint method (#815), V7 draws film grain from crystal layers, V8 pins Heal and Remove spots to the photo on the spot's edge. New photos and Reset use the latest; Update is one undoable step and never downgrades a future number. Copy/paste/sync preserve the receiving process. Persistent render keys include the resolved process from V3 on; V1/V2 keys remain unchanged. |
|
||||
| LRC-DEV-VIEWOPTIONS | Develop view options | P2 | 🟡 | `cmd:view.viewOptions`, `crates/ui-egui/src/dialogs/settings.rs` (`view_options`) | View ▸ View Options… (⌘J), the Loupe View part: Show Info Overlay with Info 1 / Info 2, and the three lines of each (none, file name, capture date, dimensions, exposure, camera, lens, camera + lens) with Use Defaults; Show Briefly When Photo Changes under each Info (one at most): with the overlay off, that Info shows for 3 s each time the loupe changes photo; General's Show message when loading or rendering photos (on by default; off, the loupe does not say "Rendering…"); applied as they change, saved with the app settings; `view.viewOptions {info1, info2, briefly, loupeMessages}` sets them for agents. Not yet: the Grid View tab, more fields (ratings, metadata, copy name), the video-frame option |
|
||||
| LRC-DEV-LOUPEOVERLAY | Loupe overlay: layout image | P2 | 🟡 | `cmd:view.chooseLayoutImage`, `cmd:view.layoutImage`, `cmd:view.layoutImageOpacity`, `cmd:view.layoutImageMatte`, `crates/ui-egui/src/panels/layout_overlay.rs` | View ▸ Loupe Overlay: a PNG with transparency (a cover layout, a banner's safe areas) fitted and centred over the loupe photo, following zoom and pan; opacity and matte (the photo darkened outside the graphic's box) in steps; ⌥⌘O shows / hides it; read off the UI thread; saved with the UI state. Not yet: the Grid and Guides overlays, moving and resizing the layout with ⌘ held, free opacity / matte sliders |
|
||||
| LRC-DEV-VIDEO | Video frame capture | P2 | ⬜ | | |
|
||||
@@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-10 | minor | LR-REM-HEAL, LR-REM-CLONE, LRC-DEV-PROCESS: process V8 pins Heal and Remove spots to the photo on the spot's edge (membrane fill of the log ratio), matches the source's grain to its surroundings and reads every spot's source at whole pixels; statuses and counts unchanged |
|
||||
| 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. |
|
||||
| 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). |
|
||||
| 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) |
|
||||
|
||||
@@ -15,7 +15,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has
|
||||
| **V4** | V3 plus calibrated global Contrast (per channel) and Blacks (per-channel/luminance mix) on raws with a camera tone curve. Whites behaves exactly as V2, both signs; its calibration is a planned follow-up. Other sources and local adjustments retain V2 operators. See [calibrated Light operators](light-v3.md). |
|
||||
| **V5** | V4 plus: a raw's tone curve rolls off into white in stops instead of reaching it within about a stop of the sensor's white, so raising Exposure keeps the highlights the sensor recorded (issue #1632). **Camera curve** (the look fitted to the embedded JPEG, or a DNG's `ProfileToneCurve`; `CameraTone`): past its last knot `CameraTone::apply_rolloff` closes the gap to white by `gap / (1 + c·(2^t − 1))` at `t` stops past the knot, with `c` matching the curve's slope there and the gap halving every stop in the end (`tone::ROLLOFF_STOPS`); `ToneMap::camera_rolloff_hdr` builds the table from it. Under V1 to V4 the curve past its last knot (fitted only to camera JPEG tones below 0.85, so 1 to 3 stops below the sensor's white on most photos) closes on white exponentially in linear light: the sensor's white renders at 8-bit 246 to 254 at Exposure 0 and 254 to 255 from Exposure +1. On the 11 CC0 corpus files with a fitted look (8 Sony, 2 Nikon, 1 Fujifilm) it now renders at 239 to 250 at Exposure 0 and 247 to 253 at +1. A DNG curve that reaches white at the sensor's white renders as before. **Generic curve** (raws without a camera curve, `ToneMap::rolloff_hdr`): from half a stop below its white point (`tone::GENERIC_KNEE_STOPS`) the same shoulder takes over, with the extended Reinhard curve's value and slope at the join, where V1 to V4 clip at the white point (scene 1.18 at default settings, ¼ stop above the sensor's white). The sensor's white renders at about 235, 248 and 252 at Exposure 0, +1 and +2 (V1 to V4: 239, 255, 255; the CC0 Canon R8 file and 6 CC0 DNGs without a camera curve). Content past the old clip point, such as a clipped sky, now renders up to 15 codes below white at Exposure 0 and reaches 255 about 5 stops past the sensor's white. Below the last knot or the join, JPEGs and other display-referred sources, and the camera fit itself are unchanged; CPU and GPU share the tone LUT. |
|
||||
| **V6** | V5 plus: colour noise reduction filters the linear colour differences R−Y and B−Y with the joint method (issue #815, `docs/nr-color-joint.md`): edge-aware weights from a denoised guide shared by both differences, anisotropic diffusion over scales, a brake for isolated colour specks; Y is kept exactly. V1 to V5 keep the blurred chromaticity (`local::denoise`). CPU (`local::denoise`) and GPU (`render::denoise`) branch on `local::joint_colour_nr`. Renders with Color 0 are the same as V2's. |
|
||||
| **V7** (the latest) | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. |
|
||||
| **V7** | V6 plus: film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 to V6 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain don't depend on this. |
|
||||
| **V8** (the latest) | V7 plus: Heal spots, and Remove spots with their automatic source, are pinned to the photo on the spot's edge (`spots::pinned`). The patch is the source times `e^P`, `P` the membrane fill (`lightcraft_inpaint::membrane_fill`) of the log ratio of photo to source, known only on the ring of pixels touching the spot and blurred there over the outside only (1.5 px), so the patch meets its surroundings at the edge, takes nothing from features that don't touch it, and carries the source's texture at its contrast relative to the new light. The source's fine detail (log luminance minus a 1.5 px blur) is scaled to the detail around the spot, by the ratio of medians around the spot (1.05 to 2 radii) and inside the source (0.9 radii), within 0.5 to 2×. Every spot, Clone included, reads its source at whole pixels (read between pixels, bilinear sampling halved the grain). V1 to V7 keep the source plus a Gaussian-weighted average of the difference around the spot (σ 0.6 radii) in linear light. Fill is unchanged. CPU and GPU branch on `spots::HealMethod`; the GPU renderer reads the image back for the spot stage on V8 photos with spots and keeps the rest of the render on the device. Renders without Heal, Remove or Clone spots are the same as V7's. |
|
||||
|
||||
## The rule
|
||||
|
||||
@@ -111,6 +112,7 @@ extra field and retain their existing cached renders. No cache-version bump is n
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-10 | minor | V8: Heal and Remove spots pinned to the photo on the spot's edge in log space, source detail matched to the surroundings, sources read at whole pixels |
|
||||
| 2026-11-07 | minor | V7: film grain from crystal layers ([grain.md](grain.md)); V1 to V6 keep their value noise |
|
||||
| 2026-11-05 | minor | V5: a raw's tone curve rolls off into white in stops, so raising Exposure keeps recorded highlights (#1632) |
|
||||
| 2026-10-12 | minor | Calibrated Contrast and Blacks, V2 Whites, resolved-process cache keys and number coordination |
|
||||
@@ -2,6 +2,15 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Heal meets its surroundings (process 8)
|
||||
- A healed spot now meets the photo exactly at its edge: on a gradient (a sky, a shaded wall, a cheek) it no longer
|
||||
leaves a faint disc or ring, and a dark line near the spot that the spot doesn't touch no longer smudges into it.
|
||||
Texture taken from a brighter or darker area keeps its contrast relative to the light where it lands, instead of
|
||||
turning blotchy in shadows or flat in highlights, and the patch takes the grain of the area around it. Heal, Remove
|
||||
and Clone read their source at whole pixels, so a patch is no longer smoother than the photo around it. This is
|
||||
rendering process 8: new photos (and Reset) get it, photos you already edited keep their look until you choose
|
||||
Photo ▸ Update to Current Process. See [process versions](process-versions.md).
|
||||
|
||||
### Film grain that looks like film (process V7)
|
||||
- Grain now comes from a simulated emulsion of crystal layers (after Aurélien Pierre's model): dense, soft and cloudy
|
||||
rather than dots on top of the photo. It fades out towards black and white as on a print, so shadows keep their depth
|
||||
|
||||
Reference in new issue
Block a user