Skip to content

armgit / kokon

Public Imported from GitHub
0

Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.

Brushed edits and Expand: colour match at the seam, Replace clears the old object

Gabriele Lozuponef1b4afa3929c
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rs
index 4424d80..2bc2ade 100644
--- a/crates/qls-core/src/engine.rs
+++ b/crates/qls-core/src/engine.rs
@@ -1146,7 +1146,7 @@ impl Engine {
let prepared = tokio::task::spawn_blocking(move || pipeline::prepare(&plan2, &prompt, seed, &images, mask_img.as_ref(), &opts))
.await
.map_err(AppError::internal)??;
- let pipeline::PreparedJob { request: mut sd_req, post } = prepared;
+ let pipeline::PreparedJob { request: mut sd_req, mut post } = prepared;
if let Some(what) = caps.mac_engine_unsupported(&sd_req) {
return Err(AppError::new(ErrorCode::Unsupported, format!("Kokon's Mac engine (experimental) does not do {what} yet."))
.suggest("Turn it off in Settings → Performance to use the standard engine for this."));
@@ -1158,6 +1158,8 @@ impl Engine {
enhanced = self.enhance_prompt(id, &client, &caps, &cfg, plan.mode, &request.prompt, &sd_req.ref_images, seed).await?;
if let Some(text) = &enhanced {
sd_req.prompt = pipeline::enhanced_prompt(&request.prompt, text);
+ // The rewrite understood a transparency request the keywords missed: keep the alpha.
+ post.keep_alpha |= pipeline::rewrite_wants_transparency(text);
}
}
// Prompt+ review: the prompt is the result; the user's next job makes the image.
diff --git a/crates/qls-core/src/imaging.rs b/crates/qls-core/src/imaging.rs
index 409eda3..0aacd1b 100644
--- a/crates/qls-core/src/imaging.rs
+++ b/crates/qls-core/src/imaging.rs
@@ -185,8 +185,14 @@ fn png_err(e: png::EncodingError) -> AppError {
AppError::new(ErrorCode::Internal, "Failed to encode PNG.").detail(e.to_string())
}
+/// JPEG has no alpha: transparent pixels are flattened onto white, not shown with the colour
+/// hidden under alpha 0 (Qwen-Image's RGBA output leaves e.g. purple there: purple thumbnails).
pub fn encode_jpeg(img: &RgbaImage, quality: u8) -> Result<Vec<u8>, AppError> {
- let rgb = DynamicImage::ImageRgba8(img.clone()).into_rgb8();
+ let rgb = image::RgbImage::from_fn(img.width(), img.height(), |x, y| {
+ let p = img.get_pixel(x, y);
+ let a = p[3] as u32;
+ image::Rgb(std::array::from_fn(|c| ((p[c] as u32 * a + 255 * (255 - a) + 127) / 255) as u8))
+ });
let mut out = Vec::new();
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
rgb.write_with_encoder(enc).map_err(|e| AppError::new(ErrorCode::Internal, "Failed to encode JPEG.").detail(e.to_string()))?;
@@ -426,12 +432,16 @@ pub fn outpaint_mask(size: Size, keep: Rect, overlap: crate::geometry::Expansion
}
/// Mask used to paste the original back into an outpainted result: 255 inside the
-/// original, ramping to 0 across `feather_px` on edges that were expanded.
+/// original, ramping (smoothstep) to 0 across `feather_px` on edges that were expanded.
pub fn paste_back_mask(size: Size, expanded: crate::geometry::Expansion, feather_px: u32) -> GrayImage {
let f = feather_px.max(1) as f32;
GrayImage::from_fn(size.width, size.height, |x, y| {
let mut v = 1.0f32;
- let ramp = |d: u32| ((d as f32 + 0.5) / f).min(1.0);
+ // Smoothstep: a linear ramp shows its two ends as faint lines on flat areas.
+ let ramp = |d: u32| {
+ let t = ((d as f32 + 0.5) / f).min(1.0);
+ t * t * (3.0 - 2.0 * t)
+ };
if expanded.left > 0 {
v = v.min(ramp(x));
}
@@ -448,29 +458,67 @@ pub fn paste_back_mask(size: Size, expanded: crate::geometry::Expansion, feather
})
}
+/// The original's pixels where `paste` < 255 (its blend band at expanded edges), mirrored across
+/// the nearest expanded edge onto a `canvas`-sized image (the original sits at `rect`), and where
+/// they landed. The truth to compare the new area against just outside the seam.
+pub fn mirror_band(source: &RgbaImage, paste: &GrayImage, rect: Rect, expanded: crate::geometry::Expansion, canvas: Size) -> (RgbaImage, GrayImage) {
+ let mut truth = RgbaImage::new(canvas.width, canvas.height);
+ let mut known = GrayImage::new(canvas.width, canvas.height);
+ let (w, h) = (source.width(), source.height());
+ for (x, y, p) in paste.enumerate_pixels() {
+ if p[0] == 255 {
+ continue;
+ }
+ // Nearest expanded edge, and the point as far outside it as (x, y) is inside.
+ let sides = [
+ (expanded.left > 0, x, (rect.x as i64 - 1 - x as i64, (rect.y + y) as i64)),
+ (expanded.right > 0, w - 1 - x, ((rect.right() + (w - 1 - x)) as i64, (rect.y + y) as i64)),
+ (expanded.top > 0, y, ((rect.x + x) as i64, rect.y as i64 - 1 - y as i64)),
+ (expanded.bottom > 0, h - 1 - y, ((rect.x + x) as i64, (rect.bottom() + (h - 1 - y)) as i64)),
+ ];
+ let Some(&(_, _, (mx, my))) = sides.iter().filter(|s| s.0).min_by_key(|s| s.1) else { continue };
+ if mx < 0 || my < 0 || mx >= canvas.width as i64 || my >= canvas.height as i64 {
+ continue;
+ }
+ truth.put_pixel(mx as u32, my as u32, *source.get_pixel(x, y));
+ known.put_pixel(mx as u32, my as u32, Luma([255]));
+ }
+ (truth, known)
+}
+
/// Replaces the pixels where `mask` > 127 by a smooth continuation of the pixels around
/// them (push-pull: weighted averages down a pyramid, then blended back up). Known pixels
/// stay exact. Erases content before a removal so the model cannot copy it back.
pub fn fill_masked(img: &RgbaImage, mask: &GrayImage) -> RgbaImage {
assert_eq!(img.dimensions(), mask.dimensions());
- struct Level {
+ let (w, h) = (img.width() as usize, img.height() as usize);
+ let color = img.pixels().map(|p| [p[0] as f32, p[1] as f32, p[2] as f32, p[3] as f32]).collect();
+ let weight = mask.pixels().map(|m| if m[0] > 127 { 0.0 } else { 1.0 }).collect();
+ let base = push_pull(w, h, color, weight, [128.0, 128.0, 128.0, 255.0]);
+ let mut out = img.clone();
+ for (i, (p, m)) in out.pixels_mut().zip(mask.pixels()).enumerate() {
+ if m[0] > 127 {
+ *p = Rgba(base[i].map(|v| v.round().clamp(0.0, 255.0) as u8));
+ }
+ }
+ out
+}
+
+/// Push-pull fill of a `w`×`h` grid: where `weight` < 1, values blend toward the bilinearly
+/// upsampled weighted means of a coarser pyramid level (fully known cells stay exact).
+fn push_pull<const N: usize>(w: usize, h: usize, color: Vec<[f32; N]>, weight: Vec<f32>, empty: [f32; N]) -> Vec<[f32; N]> {
+ struct Level<const N: usize> {
w: usize,
h: usize,
- color: Vec<[f32; 4]>,
+ color: Vec<[f32; N]>,
weight: Vec<f32>,
}
- let (w, h) = (img.width() as usize, img.height() as usize);
- let mut levels = vec![Level {
- w,
- h,
- color: img.pixels().map(|p| [p[0] as f32, p[1] as f32, p[2] as f32, p[3] as f32]).collect(),
- weight: mask.pixels().map(|m| if m[0] > 127 { 0.0 } else { 1.0 }).collect(),
- }];
+ let mut levels = vec![Level { w, h, color, weight }];
// Push: each coarser pixel is the weighted mean of its (up to) 4 children.
while levels.last().map(|l| l.w > 1 || l.h > 1).unwrap() {
let cur = levels.last().unwrap();
let (nw, nh) = (cur.w.div_ceil(2), cur.h.div_ceil(2));
- let mut csum = vec![[0f32; 4]; nw * nh];
+ let mut csum = vec![[0f32; N]; nw * nh];
let mut wsum = vec![0f32; nw * nh];
for y in 0..cur.h {
for x in 0..cur.w {
@@ -482,14 +530,14 @@ pub fn fill_masked(img: &RgbaImage, mask: &GrayImage) -> RgbaImage {
wsum[j] += wt;
}
}
- let color = csum.iter().zip(&wsum).map(|(c, &s)| if s > 0.0 { c.map(|v| v / s) } else { [128.0, 128.0, 128.0, 255.0] }).collect();
+ let color = csum.iter().zip(&wsum).map(|(c, &s)| if s > 0.0 { c.map(|v| v / s) } else { empty }).collect();
levels.push(Level { w: nw, h: nh, color, weight: wsum.iter().map(|s| s.min(1.0)).collect() });
}
// Pull: unknown (or partly known) pixels take the bilinearly upsampled coarser level.
for l in (0..levels.len() - 1).rev() {
let (fine, coarse) = levels.split_at_mut(l + 1);
let (f, c) = (&mut fine[l], &coarse[0]);
- let sample = |x: usize, y: usize| -> [f32; 4] {
+ let sample = |x: usize, y: usize| -> [f32; N] {
let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (c.w - 1) as f32);
let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (c.h - 1) as f32);
let (x0, y0) = (fx as usize, fy as usize);
@@ -510,14 +558,105 @@ pub fn fill_masked(img: &RgbaImage, mask: &GrayImage) -> RgbaImage {
}
}
}
- let base = &levels[0];
- let mut out = img.clone();
- for (i, (p, m)) in out.pixels_mut().zip(mask.pixels()).enumerate() {
- if m[0] > 127 {
- *p = Rgba(base.color[i].map(|v| v.round().clamp(0.0, 255.0) as u8));
+ levels.swap_remove(0).color
+}
+
+/// Low-frequency colour difference `truth` − `generated` on a coarse grid over `generated`:
+/// measured where `known` > 0 (weighted by it) and spread smoothly everywhere else. Lets a
+/// generated area take on the colour of the original pixels it meets at a paste border (the
+/// model's colour cast), without touching detail.
+pub struct ColorShift {
+ w: usize,
+ h: usize,
+ cell: f32,
+ d: Vec<[f32; 3]>,
+}
+
+/// Grid cells along the longer side of a [`ColorShift`]: coarse on purpose, only the cast is wanted.
+const SHIFT_CELLS: u32 = 96;
+
+/// `truth` and `known` share a size and sit at `at` in `generated`; each channel's shift is
+/// capped at ±`max`. None when nothing is known.
+pub fn color_shift(generated: &RgbaImage, truth: &RgbaImage, known: &GrayImage, at: (u32, u32), max: f32) -> Option<ColorShift> {
+ assert_eq!(truth.dimensions(), known.dimensions());
+ let cell = generated.width().max(generated.height()).div_ceil(SHIFT_CELLS).max(1);
+ let (w, h) = (generated.width().div_ceil(cell) as usize, generated.height().div_ceil(cell) as usize);
+ let mut sum = vec![[0f32; 3]; w * h];
+ let mut wsum = vec![0f32; w * h];
+ for (x, y, k) in known.enumerate_pixels() {
+ let (gx, gy) = (x + at.0, y + at.1);
+ if k[0] == 0 || gx >= generated.width() || gy >= generated.height() {
+ continue;
+ }
+ let (t, g, wt) = (truth.get_pixel(x, y), generated.get_pixel(gx, gy), k[0] as f32 / 255.0);
+ let j = (gy / cell) as usize * w + (gx / cell) as usize;
+ for c in 0..3 {
+ sum[j][c] += (t[c] as f32 - g[c] as f32) * wt;
+ }
+ wsum[j] += wt;
+ }
+ if wsum.iter().all(|&s| s == 0.0) {
+ return None;
+ }
+ // A cell is fully trusted once a tenth of it is known.
+ let full = (cell * cell) as f32 * 0.1;
+ let d = sum.iter().zip(&wsum).map(|(s, &n)| if n > 0.0 { s.map(|v| (v / n).clamp(-max, max)) } else { [0.0; 3] }).collect();
+ let weight = wsum.iter().map(|&n| (n / full).min(1.0)).collect();
+ let mut d = push_pull(w, h, d, weight, [0.0; 3]);
+ // Smooth: detail differences inside the band must not print as blotches.
+ for _ in 0..2 {
+ d = box_cells(&d, w, h, 2);
+ }
+ Some(ColorShift { w, h, cell: cell as f32, d })
+}
+
+/// Box blur of a `w`×`h` grid, radius `r` cells, edges clamped.
+fn box_cells(d: &[[f32; 3]], w: usize, h: usize, r: usize) -> Vec<[f32; 3]> {
+ let pass = |src: &[[f32; 3]], horizontal: bool| -> Vec<[f32; 3]> {
+ (0..w * h)
+ .map(|i| {
+ let (x, y) = (i % w, i / w);
+ let (lo, hi) = if horizontal { (x.saturating_sub(r), (x + r).min(w - 1)) } else { (y.saturating_sub(r), (y + r).min(h - 1)) };
+ let mut s = [0f32; 3];
+ for k in lo..=hi {
+ let v = if horizontal { src[y * w + k] } else { src[k * w + x] };
+ for c in 0..3 {
+ s[c] += v[c];
+ }
+ }
+ s.map(|v| v / (hi - lo + 1) as f32)
+ })
+ .collect()
+ };
+ pass(&pass(d, true), false)
+}
+
+impl ColorShift {
+ /// The shift at pixel (`x`, `y`) of the generated image (bilinear between cell centres).
+ pub fn at(&self, x: u32, y: u32) -> [f32; 3] {
+ let fx = ((x as f32 + 0.5) / self.cell - 0.5).clamp(0.0, (self.w - 1) as f32);
+ let fy = ((y as f32 + 0.5) / self.cell - 0.5).clamp(0.0, (self.h - 1) as f32);
+ let (x0, y0) = (fx as usize, fy as usize);
+ let (x1, y1) = ((x0 + 1).min(self.w - 1), (y0 + 1).min(self.h - 1));
+ let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
+ let p = |x: usize, y: usize| self.d[y * self.w + x];
+ let (a, b, c, e) = (p(x0, y0), p(x1, y0), p(x0, y1), p(x1, y1));
+ std::array::from_fn(|k| (a[k] * (1.0 - tx) + b[k] * tx) * (1.0 - ty) + (c[k] * (1.0 - tx) + e[k] * tx) * ty)
+ }
+
+ /// Adds the shift to `img` (the generated image), scaled per pixel by `weight` (0..1).
+ pub fn apply(&self, img: &mut RgbaImage, weight: impl Fn(u32, u32) -> f32) {
+ for (x, y, p) in img.enumerate_pixels_mut() {
+ let wt = weight(x, y);
+ if wt <= 0.0 {
+ continue;
+ }
+ let d = self.at(x, y);
+ for c in 0..3 {
+ p[c] = (p[c] as f32 + d[c] * wt).round().clamp(0.0, 255.0) as u8;
+ }
}
}
- out
}
/// Colors for marking an area on a guide image, as named in the prompt.
@@ -572,6 +711,34 @@ pub fn highlight(img: &RgbaImage, mask: &GrayImage, color: [u8; 3]) -> RgbaImage
mod fill_tests {
use super::*;
+ #[test]
+ fn color_shift_takes_the_cast_measured_in_the_band_and_nothing_else() {
+ // A generated image warmer than the truth; only a band at the truth's left is known.
+ let truth = RgbaImage::from_pixel(300, 200, Rgba([120, 120, 120, 255]));
+ let generated = RgbaImage::from_pixel(400, 200, Rgba([130, 125, 120, 255]));
+ let known = GrayImage::from_fn(300, 200, |x, _| Luma([if x < 30 { 255 } else { 0 }]));
+ let s = color_shift(&generated, &truth, &known, (100, 0), 32.0).unwrap();
+ for (x, y) in [(0, 0), (50, 100), (110, 150), (399, 199)] {
+ let d = s.at(x, y);
+ assert!((d[0] + 10.0).abs() < 0.5 && (d[1] + 5.0).abs() < 0.5 && d[2].abs() < 0.5, "{x},{y}: {d:?}");
+ }
+ let mut g = generated.clone();
+ s.apply(&mut g, |x, _| if x < 100 { 1.0 } else { 0.0 });
+ assert_eq!(g.get_pixel(10, 10).0, [120, 120, 120, 255]);
+ assert_eq!(g.get_pixel(200, 10).0, [130, 125, 120, 255]);
+ // No cast, no change; nothing known, no shift.
+ assert!(color_shift(&truth, &truth, &known, (0, 0), 32.0).unwrap().at(5, 5).iter().all(|v| v.abs() < 1e-3));
+ assert!(color_shift(&truth, &truth, &GrayImage::new(300, 200), (0, 0), 32.0).is_none());
+ }
+
+ #[test]
+ fn color_shift_is_capped() {
+ let truth = RgbaImage::from_pixel(64, 64, Rgba([0, 0, 0, 255]));
+ let generated = RgbaImage::from_pixel(64, 64, Rgba([200, 200, 200, 255]));
+ let s = color_shift(&generated, &truth, &GrayImage::from_pixel(64, 64, Luma([255])), (0, 0), 24.0).unwrap();
+ assert!((s.at(30, 30)[0] + 24.0).abs() < 1e-3);
+ }
+
#[test]
fn fill_masked_keeps_known_pixels_and_continues_colors() {
// Left half blue, right half green, a red square across the boundary.
@@ -635,6 +802,16 @@ mod tests {
assert!(decode_engine_image(&png, 4096).is_err(), "larger than the plan allows");
}
+ #[test]
+ fn jpeg_flattens_transparency_onto_white() {
+ // Left half: purple under alpha 0 (Qwen-Image's RGBA background); right half opaque red.
+ let img = RgbaImage::from_fn(64, 32, |x, _| if x < 32 { Rgba([155, 75, 196, 0]) } else { Rgba([200, 0, 0, 255]) });
+ let back = decode_image(&encode_jpeg(&img, 95).unwrap()).unwrap().pixels;
+ let (bg, fg) = (back.get_pixel(8, 16), back.get_pixel(56, 16));
+ assert!(bg.0[..3].iter().all(|&c| c > 245), "{bg:?}");
+ assert!(fg[0] > 180 && fg[1] < 30, "{fg:?}");
+ }
+
/// Builds a JPEG with an EXIF APP1 segment carrying the given orientation.
fn jpeg_with_orientation(img: &RgbaImage, orientation: u16) -> Vec<u8> {
let jpeg = encode_jpeg(img, 95).unwrap();
diff --git a/crates/qls-core/src/pipeline.rs b/crates/qls-core/src/pipeline.rs
index c8f7294..3c96cd4 100644
--- a/crates/qls-core/src/pipeline.rs
+++ b/crates/qls-core/src/pipeline.rs
@@ -51,8 +51,10 @@ pub struct PreparedJob {
pub enum PostKind {
Plain,
- Inpaint { source: RgbaImage, region: Rect, blend: GrayImage },
- Outpaint { source: RgbaImage, feather: u32 },
+ /// `regen`: where the model regenerated pixels that are pasted back at 0 (region size),
+ /// the band that measures its colour cast; None skips the colour match.
+ Inpaint { source: RgbaImage, region: Rect, blend: GrayImage, regen: Option<GrayImage> },
+ Outpaint { source: RgbaImage, feather: u32, match_colors: bool },
}
pub struct PostProcess {
@@ -105,12 +107,27 @@ fn is_binary(m: &GrayImage) -> bool {
const RGBA_PREFIX: &str = "This is an RGBA image with transparency.";
const RGBA_SUFFIX: &str = "The image has alpha channel and the background is transparent.";
-/// True when the prompt asks for transparency (e.g. "transparent background", "remove the background").
+/// True when the prompt asks for transparency (e.g. "transparent background", "remove the background"),
+/// in the user's own words: English plus Italian, Spanish, French, German and Portuguese (Prompt+
+/// rewrites in English, but this looks at what the user typed).
pub fn wants_transparency(prompt: &str) -> bool {
let p = prompt.to_lowercase();
- ["transparent", "transparency", "alpha channel", "rgba", "no background", "without background", "remove the background", "remove background", "cut out", "cutout"]
- .iter()
- .any(|k| p.contains(k))
+ [
+ // en; "transpar" also covers es/pt "transparente", fr/de "transparent"
+ "transpar", "alpha channel", "rgba", "no background", "without background", "remove the background", "remove background", "cut out", "cutout",
+ // it
+ "traspar", "senza sfondo", "rimuovi lo sfondo", "togli lo sfondo", "elimina lo sfondo", "scontorn",
+ // es
+ "sin fondo", "quita el fondo", "quitar el fondo", "elimina el fondo", "eliminar el fondo",
+ // fr
+ "sans fond", "sans arrière-plan", "supprime l'arrière-plan", "supprimer l'arrière-plan", "détour",
+ // de
+ "ohne hintergrund", "hintergrund entfernen", "entferne den hintergrund", "freistell",
+ // pt
+ "sem fundo", "remova o fundo", "remover o fundo", "tire o fundo",
+ ]
+ .iter()
+ .any(|k| p.contains(k))
}
/// Inpaint instruction: `<image1>` is the region (blurred out where content is removed),
@@ -131,7 +148,7 @@ pub fn inpaint_prompt(action: InpaintAction, prompt: &str, color: &str) -> Strin
)
}
InpaintAction::Replace => format!(
- "In <image1>, replace what is inside {area} with {what}. Match the scene's lighting, perspective, scale and style so it looks naturally part of the image. {keep}"
+ "In <image1>, {area} has been blurred out to clear what was there. Fill the blurred area with {what}. Match the scene's lighting, perspective, scale and style so it looks naturally part of the image. {keep}"
),
InpaintAction::Add => format!(
"In <image1>, add {what} inside {area}, fitting it naturally into the scene with matching lighting, perspective, scale and shadows. {keep}"
@@ -157,12 +174,26 @@ pub fn effective_prompt(plan: &Plan, prompt: &str) -> String {
}
}
+/// True when a Prompt+ rewrite asks for a transparent *background* ("background to be fully
+/// transparent", "transparent background", "full transparency", "alpha channel"): the rewrite is
+/// English whatever the user typed, so this catches other languages and typos ("trasperenza").
+/// A transparent object ("a transparent glass vase") does not count.
+pub fn rewrite_wants_transparency(enhanced: &str) -> bool {
+ static RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
+ regex::Regex::new(
+ r"(?i)\bbackground\s+(?:is\s+|to\s+be\s+|becomes?\s+|made\s+)?(?:fully\s+|completely\s+|entirely\s+)?transparent\b|\btransparent\s+background\b|\bfull\s+transparency\b|\balpha\s+channel\b|\btransparent\s+png\b",
+ )
+ .unwrap()
+ });
+ RE.is_match(enhanced)
+}
+
/// The prompt sent for an enhanced job (text-to-image, compose, edit, combine): the enhancer's text,
-/// wrapped for transparency when the user's own words asked for it (not the rewrite's, which
-/// may mention "transparent glass").
+/// wrapped for transparency when the user's own words asked for it, or the rewrite asks for a
+/// transparent background (not merely a transparent object: "transparent glass").
pub fn enhanced_prompt(original: &str, enhanced: &str) -> String {
let p = enhanced.trim();
- if wants_transparency(original) && !p.starts_with(RGBA_PREFIX) {
+ if (wants_transparency(original) || rewrite_wants_transparency(p)) && !p.starts_with(RGBA_PREFIX) {
return format!("{RGBA_PREFIX} {}. {RGBA_SUFFIX}", p.trim_end_matches('.'));
}
p.to_string()
@@ -256,7 +287,7 @@ pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mas
blend = imaging::dilate(&blend, ((region.width.max(region.height) as f64) * 0.01).round().max(4.0) as u32);
}
if is_binary(&blend) {
- let r = ((region.width.max(region.height) as f64) * 0.006).round().max(3.0) as u32;
+ let r = ((region.width.max(region.height) as f64) * 0.012).round().max(3.0) as u32;
blend = imaging::feather(&imaging::dilate(&blend, r / 2), r);
}
// Backend mask (working resolution): binary, grown to cover the soft edge.
@@ -266,10 +297,11 @@ pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mas
let mut m_canvas = GrayImage::from_pixel(wc.canvas.width, wc.canvas.height, Luma([0]));
image::imageops::replace(&mut m_canvas, &m_work, wc.content_offset.0 as i64, wc.content_offset.1 as i64);
- // Image 1: the region; for a removal with the content already blurred away, so
- // the model rebuilds background instead of copying the object back.
+ // Image 1: the region; for a removal or a replacement with the content already
+ // blurred away, so the model rebuilds the area instead of keeping the old object
+ // (a replaced bowl otherwise gets the new thing put *in* it).
let pad = |img: &RgbaImage| imaging::pad_edge(img, wc.canvas, wc.content_offset);
- let image1 = if action == InpaintAction::Remove { imaging::fill_masked(&content, &m_work) } else { content.clone() };
+ let image1 = if matches!(action, InpaintAction::Remove | InpaintAction::Replace) { imaging::fill_masked(&content, &m_work) } else { content.clone() };
// Image 2 (guide): the area marked in a color named in the prompt. The model gets
// no mask otherwise; the latent mask only discards changes outside it.
let gc = plan.references.get(1).map(|r| r.canvas).ok_or_else(|| AppError::internal("missing inpaint guide plan"))?;
@@ -292,7 +324,10 @@ pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mas
req.mask_image = Some(gray_png_b64(&m_canvas)?);
req.strength = plan.strength;
req.image_preprocess = vec!["target=init,mode=none".into(), "target=mask,mode=none,filter=nearest-exact".into(), "target=ref,mode=none".into()];
- kind = PostKind::Inpaint { source: src.clone(), region, blend };
+ // Regenerated but not pasted: the backend mask (back at region size) where the blend is ~0.
+ let back = imaging::resize_mask(&m_work, region.width, region.height);
+ let regen = GrayImage::from_fn(region.width, region.height, |x, y| Luma([if back.get_pixel(x, y)[0] > 127 && blend.get_pixel(x, y)[0] <= 8 { 255 } else { 0 }]));
+ kind = PostKind::Inpaint { source: src.clone(), region, blend, regen: Some(regen) };
}
ResolvedMode::Outpaint => {
need_images(1)?;
@@ -311,7 +346,7 @@ pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mas
let feather_final = ((op.overlap_working.left.max(op.overlap_working.right).max(op.overlap_working.top).max(op.overlap_working.bottom)) as f64
/ op.working.scale)
.round() as u32;
- kind = PostKind::Outpaint { source: src.clone(), feather: feather_final.max(2) };
+ kind = PostKind::Outpaint { source: src.clone(), feather: feather_final.max(2), match_colors: true };
}
ResolvedMode::Upscale => return Err(AppError::internal("an upscale has no diffusion request")),
}
@@ -322,6 +357,10 @@ pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mas
})
}
+/// Largest colour correction (levels per channel) at a paste border: a real cast is a few
+/// levels; more means different content, which a tint must not try to fix.
+const COLOR_MATCH_MAX: f32 = 24.0;
+
/// Turns one backend output image into the delivered image (Lanczos for any resize).
pub fn postprocess(raw: RgbaImage, post: &PostProcess) -> AppResult<RgbaImage> {
finish(crop_content(raw, post), post)
@@ -360,17 +399,42 @@ pub fn enlarge_target(post: &PostProcess) -> Option<Size> {
pub fn finish(content: RgbaImage, post: &PostProcess) -> AppResult<RgbaImage> {
Ok(match &post.kind {
PostKind::Plain => imaging::resize(&content, post.output.width, post.output.height),
- PostKind::Inpaint { source, region, blend } => {
- let patch = imaging::resize(&content, region.width, region.height);
+ PostKind::Inpaint { source, region, blend, regen } => {
+ let mut patch = imaging::resize(&content, region.width, region.height);
+ // The model's colour cast, measured just outside the pasted area, comes off the patch.
+ if let Some(regen) = regen {
+ let truth = imaging::crop(source, *region);
+ if let Some(shift) = imaging::color_shift(&patch, &truth, regen, (0, 0), COLOR_MATCH_MAX) {
+ shift.apply(&mut patch, |x, y| if blend.get_pixel(x, y)[0] > 0 { 1.0 } else { 0.0 });
+ }
+ }
let mut out = source.clone();
imaging::composite(&mut out, &patch, blend, (region.x, region.y));
out
}
- PostKind::Outpaint { source, feather } => {
+ PostKind::Outpaint { source, feather, match_colors } => {
let op = post.outpaint.as_ref().ok_or_else(|| AppError::internal("missing outpaint plan"))?;
let mut out = imaging::resize(&content, op.final_size.width, op.final_size.height);
let paste = imaging::paste_back_mask(Size::new(source.width(), source.height()), op.expansion, *feather);
- imaging::composite(&mut out, source, &paste, (op.source_rect_final.x, op.source_rect_final.y));
+ let r = op.source_rect_final;
+ if *match_colors {
+ // Colour step across the seam: the original's pixels in the paste band, mirrored
+ // onto the new area just outside it, against what the model drew there. Removed
+ // fully at the seam, fading out over half the widest expansion (a local mismatch
+ // must not tint far areas). Comparing the band with its own regenerated copy
+ // instead over-corrected where the model drew the band unlike its surroundings.
+ let (truth, known) = imaging::mirror_band(source, &paste, r, op.expansion, Size::new(out.width(), out.height()));
+ if let Some(shift) = imaging::color_shift(&out, &truth, &known, (0, 0), COLOR_MATCH_MAX) {
+ let e = op.expansion;
+ let fade = (e.left.max(e.right).max(e.top).max(e.bottom) as f32 * 0.5).max(64.0);
+ shift.apply(&mut out, |x, y| {
+ let dx = r.x.saturating_sub(x).max(x.saturating_sub(r.right().saturating_sub(1)));
+ let dy = r.y.saturating_sub(y).max(y.saturating_sub(r.bottom().saturating_sub(1)));
+ (1.0 - (dx as f32).hypot(dy as f32) / fade).clamp(0.0, 1.0)
+ });
+ }
+ }
+ imaging::composite(&mut out, source, &paste, (r.x, r.y));
out
}
})
@@ -546,6 +610,27 @@ mod tests {
let p = enhanced_prompt("a logo with transparent background", "A flat fox logo.");
assert_eq!(p, format!("{RGBA_PREFIX} A flat fox logo. {RGBA_SUFFIX}"));
assert_eq!(enhanced_prompt("transparent", &p), p, "not wrapped twice");
+ // The user's own language counts (10-30: "trasparenza" gave an opaque purple background).
+ let it = enhanced_prompt("dammi solo il soggetto con trasparenza png", "Remove the background and replace it with full transparency.");
+ assert!(it.starts_with(RGBA_PREFIX), "{it}");
+ // A typo the keywords miss: the rewrite's "transparent background" decides.
+ let typo = enhanced_prompt("dammi l'immagine con trasperenza", "Change the background to be fully transparent. Keep everything else unchanged.");
+ assert!(typo.starts_with(RGBA_PREFIX), "{typo}");
+ for r in ["A transparent glass vase on a wooden background.", "Remove the background and replace it with a sunny beach."] {
+ assert!(!rewrite_wants_transparency(r), "{r}");
+ }
+ }
+
+ #[test]
+ fn transparency_requests_in_other_languages() {
+ for p in ["sfondo trasparente", "scontorna il soggetto", "togli lo sfondo", "fondo transparente", "sin fondo", "fond transparent", "détoure le produit",
+ "ohne Hintergrund", "freistellen", "sem fundo", "Remove the background"]
+ {
+ assert!(wants_transparency(p), "{p}");
+ }
+ for p in ["un gatto sul divano", "a red car at sunset", "metti uno sfondo blu", "ein Hund im Park"] {
+ assert!(!wants_transparency(p), "{p}");
+ }
}
#[test]
@@ -931,6 +1016,28 @@ mod tests {
assert!(rm.request.prompt.contains("blurred out to remove the box"), "{}", rm.request.prompt);
assert!(center(&rm).0[..3].iter().any(|&c| c < 230), "box erased: {:?}", center(&rm));
assert_eq!(rm.request.init_image.as_ref(), Some(&rm.request.ref_images[0]));
+ // A replacement clears the old object too, so the new one is not put *in* it.
+ let (_, _, rp) = inpaint_job("a red hat", InpaintAction::Replace);
+ assert!(rp.request.prompt.contains("blurred out to clear what was there"), "{}", rp.request.prompt);
+ assert!(center(&rp).0[..3].iter().any(|&c| c < 230), "box erased: {:?}", center(&rp));
+ }
+
+ #[test]
+ fn outpaint_takes_the_original_colours_at_the_seam() {
+ // The model's new area is off-colour (the fake backend); the original is flat grey.
+ let mut img = photo(800, 600);
+ img.pixels = RgbaImage::from_pixel(800, 600, Rgba([120, 120, 120, 255]));
+ let mut r = req("more wall");
+ r.outpaint = Some(OutpaintSpec { left: 0.0, right: 50.0, top: 0.0, bottom: 0.0, units: ExpansionUnits::Percent });
+ let p = plan(&r, &PlanInputs { image_sizes: vec![img.size()], vram_total_mib: Some(16303), ..Default::default() }, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 1, std::slice::from_ref(&img), None, &BackendOptions::default()).unwrap();
+ let out = postprocess(fake_backend(p.working.width, p.working.height), &j.post).unwrap();
+ // Just past the seam: moved toward the original by the capped shift (+24, +21, −24).
+ let near = out.get_pixel(810, 300).0;
+ assert!((near[0] as i32 - 32).abs() <= 2 && (near[1] as i32 - 119).abs() <= 2 && (near[2] as i32 - 176).abs() <= 2, "{near:?}");
+ // Far from it, the model's colours; the original itself untouched.
+ assert_eq!(out.get_pixel(1150, 300), &Rgba([9, 99, 199, 255]));
+ assert_eq!(out.get_pixel(400, 300), &Rgba([120, 120, 120, 255]));
}
#[test]
diff --git a/crates/qls-core/src/planner.rs b/crates/qls-core/src/planner.rs
index bde728b..5fb9948 100644
--- a/crates/qls-core/src/planner.rs
+++ b/crates/qls-core/src/planner.rs
@@ -1127,7 +1127,9 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
_ => tier_area.unwrap().min(final_area.max(256 * 256)),
};
let area = cap_for_refs(wanted, 1.0, &mut notes);
- let p = plan_outpaint(src, exp, &limits(area, rec), 32).map_err(AppError::invalid)?;
+ // 64 working px of the original's border are regenerated and blended: narrower bands
+ // left a visible line on flat backgrounds (10-30 suit Expand).
+ let p = plan_outpaint(src, exp, &limits(area, rec), 64).map_err(AppError::invalid)?;
working = p.working;
output = p.final_size;
references.push(RefPlan { index: 0, source: src, canvas: ref_canvas(src, p.working.canvas.area(), rec) });