Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Keep a drawing's own colours when removing a coloured backdrop
KnifeLemonab29a8bb6923
diff --git a/src/Filee.Engines/Magick/BackgroundRemover.cs b/src/Filee.Engines/Magick/BackgroundRemover.csindex 90431b9b..b545b54e 100644--- a/src/Filee.Engines/Magick/BackgroundRemover.cs+++ b/src/Filee.Engines/Magick/BackgroundRemover.cs@@ -17,8 +17,10 @@ namespace Filee.Engines.Magick;/// colour, so a pale logo colour is not taken for paper. 3. Each pixel is treated as ink of some colour laid over/// the backdrop with some opacity (as GIMP's "Color to Alpha"): the opacity is how far the pixel is from the/// backdrop towards black or white, and the ink colour is recovered from it. Anti-aliased stroke edges therefore-/// stay smooth and lose their white fringe instead of becoming a jagged cut-out. 4. Lone visible pixels (noise,-/// paper grain) are cleared.+/// stay smooth and lose their white fringe instead of becoming a jagged cut-out. This only holds for a blend of+/// backdrop and ink, which lies between the two: artwork in colours of its own (a drawing on a coloured backdrop)+/// stays solid and unchanged, or un-mixing would turn it half transparent and shift its colours away from the+/// backdrop's. 4. Lone visible pixels (noise, paper grain) are cleared./// </para>/// <para>/// Optionally only the backdrop reachable from the image edge is removed, so the white inside a logo stays. This is@@ -42,6 +44,18 @@ public static class BackgroundRemover/// <summary>Smallest side of an image whose lone pixels are cleared as noise.</summary>private const int MinSpeckSize = 32;+ /// <summary>How much opacity (in 1/255) a blend may lose or gain against the way it runs: JPEG noise on a flat grey.</summary>+ private const int BlendDrop = 10;++ /// <summary>How far (per channel) the un-mixed colour of a blend may be from the ink next to it.</summary>+ private const int InkMatch = 48;++ /// <summary>Largest channel spread of a grey (a shadow un-mixing to black or grey ink).</summary>+ private const int NeutralInk = 24;++ /// <summary>Bins per channel when telling which colours the ink has.</summary>+ private const int InkBins = 16;+/// <summary>Removes the background of <paramref name="image"/> in place.</summary>/// <param name="tolerance">0-100: how different from the backdrop a pixel may be and still be removed.</param>/// <param name="keepEnclosed">Only remove the backdrop that is connected to the image edge.</param>@@ -83,7 +97,9 @@ public static class BackgroundRemover}}var full = InkOpacity(raw, cutoff);+ var distinct = Math.Min(1f, cutoff + MinSoftBand); // clearly not backdropvar enclosed = keepEnclosed ? Enclosed(raw, width, height, (cutoff + full) / 2) : null;+ var blends = Blends(pixels, raw, width, backdrop, cutoff, full);// Written into the pixel array itself: each pixel is read once, right before it is replaced.for (var y = 0; y < height; y++)@@ -100,9 +116,19 @@ public static class BackgroundRemover// Un-mix: pixel = alpha × ink + (1 − alpha) × backdrop. Laid back over the backdrop, the result// looks like the original wherever alpha is at least the raw opacity.var (br, bg, bb) = backdrop.At(x, y);- pixels[o] = Unmix(pixels[o], br, alpha);- pixels[o + 1] = Unmix(pixels[o + 1], bg, alpha);- pixels[o + 2] = Unmix(pixels[o + 2], bb, alpha);+ if (alpha < 1 && !blends[i])+ {+ // Not the edge or trace of an ink but artwork in a colour of its own (the white or blue body+ // of a drawing on a teal backdrop). Un-mixing it would turn it half transparent and push its+ // colour away from the backdrop's (teal → red), so it is solid once clearly not backdrop.+ alpha = Math.Clamp((raw[i] / 255f - cutoff) / (distinct - cutoff), 0f, 1f);+ }+ if (alpha < 1)+ {+ pixels[o] = Unmix(pixels[o], br, alpha);+ pixels[o + 1] = Unmix(pixels[o + 1], bg, alpha);+ pixels[o + 2] = Unmix(pixels[o + 2], bb, alpha);+ }}pixels[o + 3] = (byte)Math.Round(alpha * pixels[o + 3]);}@@ -146,6 +172,119 @@ public static class BackgroundRemoverreturn 1f;}+ /// <summary>+ /// The partly opaque pixels that are a blend of the backdrop and an ink (an anti-aliased stroke edge, faint pencil,+ /// a shadow on the paper), which are un-mixed; the others are artwork in a colour of its own. A blend lies between+ /// the two: it grows more transparent towards removed backdrop, and more opaque towards ink of the colour it+ /// un-mixes to. Both are needed on a coloured backdrop, where every colour un-mixes to something: the blue body of+ /// a drawing on teal un-mixes to dark navy like its outline but lies past the outline, and a grey strip between+ /// two outlines that touches the backdrop at its end un-mixes to pink, which no ink next to it has. A shadow on+ /// the paper is a blend with no ink next to it: one un-mixing to a grey of an ink in the image still counts.+ /// </summary>+ private static bool[] Blends(byte[] pixels, byte[] raw, int width, Backdrop backdrop, float cutoff, float full)+ {+ var removed = (byte)Math.Clamp(Math.Floor(cutoff * 255), 0, 255); // raw at or below: alpha 0+ var solid = (byte)Math.Clamp(Math.Ceiling(full * 255), 0, 255); // raw at or above: alpha 1++ // The colour a pixel un-mixes to: its own once it is solid.+ (byte R, byte G, byte B) Ink(int i)+ {+ var o = i * 4;+ if (raw[i] >= solid)+ return (pixels[o], pixels[o + 1], pixels[o + 2]);+ var alpha = (raw[i] / 255f - cutoff) / (full - cutoff);+ var (br, bg, bb) = backdrop.At(i % width, i / width);+ return (Unmix(pixels[o], br, alpha), Unmix(pixels[o + 1], bg, alpha), Unmix(pixels[o + 2], bb, alpha));+ }+ static bool Near((byte R, byte G, byte B) a, (byte R, byte G, byte B) b) =>+ Math.Max(Math.Abs(a.R - b.R), Math.Max(Math.Abs(a.G - b.G), Math.Abs(a.B - b.B))) <= InkMatch;++ var fromBackdrop = Flood(raw.Length, width, i => raw[i] <= removed,+ (_, from, i) => raw[i] > removed && raw[i] < solid && raw[i] + BlendDrop >= raw[from]);+ // Compared with the ink the path started from, not the previous pixel: a gradual shift adds up.+ var blends = Flood(raw.Length, width, i => raw[i] >= solid,+ (ink, from, i) => fromBackdrop[i] && raw[i] <= raw[from] + BlendDrop && Near(Ink(ink), Ink(i)));++ var inks = InkColours(pixels, raw, solid);+ for (var i = 0; i < raw.Length; i++)+ {+ if (!fromBackdrop[i] || blends[i])+ continue;+ var (r, g, b) = Ink(i);+ blends[i] = Math.Max(r, Math.Max(g, b)) - Math.Min(r, Math.Min(g, b)) <= NeutralInk && inks[Bin(r, g, b)];+ }+ return blends;+ }++ /// <summary>+ /// Pixels reached from the <paramref name="seed"/> pixels over 4-connected steps that <paramref name="step"/>+ /// (seed the path started from, from, to) allows. Seeds only count as reached when a step leads back to them.+ /// </summary>+ private static bool[] Flood(int count, int width, Func<int, bool> seed, Func<int, int, int, bool> step)+ {+ var reached = new bool[count];+ var queue = new Queue<(int Pixel, int Seed)>();+ void Spread(int from, int origin)+ {+ var x = from % width;+ if (x > 0) Visit(origin, from, from - 1);+ if (x < width - 1) Visit(origin, from, from + 1);+ if (from >= width) Visit(origin, from, from - width);+ if (from < count - width) Visit(origin, from, from + width);+ }+ void Visit(int origin, int from, int i)+ {+ if (!reached[i] && step(origin, from, i))+ {+ reached[i] = true;+ queue.Enqueue((i, origin));+ }+ }+ for (var i = 0; i < count; i++)+ {+ if (seed(i))+ Spread(i, i);+ }+ while (queue.TryDequeue(out var next))+ Spread(next.Pixel, next.Seed);+ return reached;+ }++ /// <summary>+ /// The colours of the solid ink (pixels whose raw opacity is at least <paramref name="solid"/>), in bins of 16+ /// levels per channel and widened by one bin: a pixel that un-mixes to one of them may be a trace of that ink.+ /// </summary>+ private static bool[] InkColours(byte[] pixels, byte[] raw, byte solid)+ {+ var counts = new int[InkBins * InkBins * InkBins];+ var total = 0;+ for (var i = 0; i < raw.Length; i++)+ {+ if (raw[i] < solid)+ continue;+ var o = i * 4;+ counts[Bin(pixels[o], pixels[o + 1], pixels[o + 2])]++;+ total++;+ }+ // A few stray pixels of a colour (noise, a JPEG ringing artefact) are not an ink.+ var least = Math.Max(2, total / 500);+ var inks = new bool[counts.Length];+ for (var r = 0; r < InkBins; r++)+ for (var g = 0; g < InkBins; g++)+ for (var b = 0; b < InkBins; b++)+ {+ if (counts[(r * InkBins + g) * InkBins + b] < least)+ continue;+ for (var nr = Math.Max(0, r - 1); nr <= Math.Min(InkBins - 1, r + 1); nr++)+ for (var ng = Math.Max(0, g - 1); ng <= Math.Min(InkBins - 1, g + 1); ng++)+ for (var nb = Math.Max(0, b - 1); nb <= Math.Min(InkBins - 1, b + 1); nb++)+ inks[(nr * InkBins + ng) * InkBins + nb] = true;+ }+ return inks;+ }++ private static int Bin(byte r, byte g, byte b) => ((r >> 4) * InkBins + (g >> 4)) * InkBins + (b >> 4);+/// <summary>How opaque ink of channel value <paramref name="value"/> over <paramref name="backdrop"/> must at least be.</summary>private static float Opacity(byte value, float backdrop){diff --git a/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs b/tests/Filee.Engines.Tests/BackgroundRemovalTests.csindex 86b1551c..3cc59a69 100644--- a/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs+++ b/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs@@ -238,6 +238,166 @@ public class BackgroundRemovalTests(EngineFixture fx) : IClassFixture<EngineFixtAssert.Equal(255, Pixel(high, 85, 30).A);}+ /// <summary>+ /// A drawing on a teal backdrop (issue #139): black-outlined panels in steel blue, a light blue-grey "window",+ /// red, white and light grey, and a white disc with no outline.+ /// </summary>+ private static MagickImage Drawing()+ {+ var image = new MagickImage(new MagickColor(Teal), 240, 160);+ new Drawables().StrokeColor(MagickColors.Black).StrokeWidth(3)+ .FillColor(new MagickColor(SteelBlue)).Rectangle(20, 20, 110, 80)+ .FillColor(new MagickColor(Window)).Rectangle(30, 30, 70, 70)+ .FillColor(new MagickColor(Red)).Rectangle(130, 20, 220, 80)+ .FillColor(new MagickColor(White)).Rectangle(20, 100, 60, 140)+ .FillColor(new MagickColor(LightGrey)).Rectangle(70, 100, 110, 140)+ .Draw(image);+ new Drawables().FillColor(new MagickColor(White)).Circle(170, 120, 170, 145).Draw(image);+ return image;+ }++ private const string Teal = "#1AA59A", SteelBlue = "#3E667F", Window = "#90A2A6", Red = "#F04F47",+ White = "#F5F5F5", LightGrey = "#D2D2D2";++ /// <summary>A point inside each colour of <see cref="Drawing"/>.</summary>+ public static TheoryData<int, int, string> DrawingColours => new()+ {+ { 90, 50, SteelBlue }, { 50, 50, Window }, { 175, 50, Red }, { 40, 120, White }, { 90, 120, LightGrey },+ { 170, 120, White },+ };++ private static void AssertKept(IMagickImage<byte> image, int x, int y, string colour)+ {+ var expected = new MagickColor(colour);+ var pixel = Pixel(image, x, y);+ Assert.True(pixel.A == 255+ && Math.Abs(pixel.R - expected.R) <= 6 && Math.Abs(pixel.G - expected.G) <= 6 && Math.Abs(pixel.B - expected.B) <= 6,+ $"({x}, {y}): {pixel} instead of {colour}");+ }++ [Theory]+ [MemberData(nameof(DrawingColours))]+ public void A_drawing_on_a_coloured_backdrop_keeps_its_colours(int x, int y, string colour)+ {+ // Every colour of the drawing was taken for ink over teal: un-mixed, the blue body became half transparent+ // magenta and the white and grey parts pink.+ using var image = Removed(Drawing());++ AssertKept(image, x, y, colour);+ Assert.Equal(0, Pixel(image, 5, 5).A);+ Assert.Equal(0, Pixel(image, 125, 150).A);+ }++ [Fact]+ public void Edges_on_a_coloured_backdrop_lose_the_backdrop_without_turning_red()+ {+ using var image = Removed(Drawing());++ // The anti-aliased rim of the white disc and of the black outlines.+ var visible = 0;+ for (var y = 90; y < 160; y++)+ {+ for (var x = 120; x < 240; x++)+ {+ var pixel = Pixel(image, x, y);+ if (pixel.A == 0)+ continue;+ visible++;+ Assert.True(pixel.R >= 240 && pixel.G >= 240 && pixel.B >= 240, $"disc ({x}, {y}): {pixel}");+ }+ }+ Assert.True(visible > 1500, visible.ToString());+ for (var x = 125; x < 225; x++)+ {+ var pixel = Pixel(image, x, 18); // above the red panel's outline+ if (pixel.A > 0)+ Assert.True(pixel.R < 64 && pixel.G < 64 && pixel.B < 64, $"outline ({x}, 18): {pixel}");+ }+ }++ [Theory]+ [InlineData("#BFE3DA")] // mint+ [InlineData("#F2D7A6")] // sand+ public void A_white_logo_with_a_shadow_stays_white(string backdrop)+ {+ // A white label with heavy black lettering and a drop shadow in a darker shade of the backdrop. The black set+ // the ink opacity, and the white was un-mixed to half transparent white.+ var shade = new MagickColor(backdrop);+ shade = new MagickColor((byte)(shade.R * 6 / 10), (byte)(shade.G * 6 / 10), (byte)(shade.B * 6 / 10));+ using var image = new MagickImage(new MagickColor(backdrop), 240, 160);+ new Drawables()+ .FillColor(shade).Rectangle(48, 48, 208, 128)+ .FillColor(MagickColors.White).Rectangle(40, 40, 200, 120)+ .FillColor(MagickColors.Black).Rectangle(60, 60, 180, 100)+ .Draw(image);++ Removed(image);++ AssertKept(image, 120, 50, "#FFFFFF");+ AssertKept(image, 50, 110, "#FFFFFF");+ AssertKept(image, 120, 80, "#000000");+ Assert.Equal(0, Pixel(image, 5, 5).A);+ var shadow = Pixel(image, 204, 100);+ Assert.True(shadow.A > 0 && Math.Max(shadow.R, Math.Max(shadow.G, shadow.B)) < 160, $"shadow: {shadow}");+ }++ [Fact]+ public async Task A_palette_png_drawing_keeps_its_colours_with_the_built_in_preset()+ {+ var dir = fx.NewFolder();+ var source = Path.Combine(dir, "drawing.png");+ using (var image = Drawing())+ image.Write(source, MagickFormat.Png8);+ using (var written = new MagickImage(source))+ Assert.Equal(ColorType.Palette, written.ColorType);+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "remove-background");++ var job = await fx.ConvertAsync([source], preset);++ Assert.Equal(JobState.Completed, job.State);+ using var result = new MagickImage(job.Outputs.Single());+ Assert.Equal(0, Pixel(result, 5, 5).A);+ // Png8 quantises the drawing: compare with the palette colours that were written, not the drawn ones.+ using var palette = new MagickImage(source);+ foreach (var (x, y) in new[] { (90, 50), (50, 50), (175, 50), (40, 120), (90, 120), (170, 120) })+ AssertKept(result, x, y, Pixel(palette, x, y).ToHexString()[..7]);+ }++ [Fact]+ public async Task A_gray_and_alpha_png_keeps_its_light_grey_with_the_built_in_preset()+ {+ // Grey + alpha PNG: a light grey label with a large black block on a mid grey backdrop, one corner already+ // transparent. The label was un-mixed to half transparent white.+ var dir = fx.NewFolder();+ var source = Path.Combine(dir, "gray.png");+ using (var image = new MagickImage(new MagickColor("#808080"), 200, 140))+ {+ new Drawables().StrokeColor(MagickColors.Black).StrokeWidth(4).FillColor(new MagickColor("#F0F0F0"))+ .Rectangle(40, 30, 160, 110)+ .StrokeColor(MagickColors.Transparent).FillColor(MagickColors.Black).Rectangle(50, 50, 150, 90)+ .Draw(image);+ image.Alpha(AlphaOption.Set);+ using (var pixels = image.GetPixels())+ for (var y = 0; y < 20; y++)+ for (var x = 170; x < 200; x++)+ pixels.SetPixel(x, y, [0, 0, 0, 0]);+ image.ColorType = ColorType.GrayscaleAlpha;+ image.Write(source, MagickFormat.Png);+ }+ using (var written = new MagickImage(source))+ Assert.Equal(ColorType.GrayscaleAlpha, written.ColorType);+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "remove-background");++ var job = await fx.ConvertAsync([source], preset);++ Assert.Equal(JobState.Completed, job.State);+ using var result = new MagickImage(job.Outputs.Single());+ Assert.Equal(0, Pixel(result, 5, 5).A);+ Assert.Equal(0, Pixel(result, 185, 10).A);+ AssertKept(result, 100, 40, "#F0F0F0");+ AssertKept(result, 100, 70, "#000000");+ }+[Fact]public async Task Jpg_signature_becomes_a_transparent_png_with_the_built_in_preset(){