Skip to content

armgit / Filee

Public Imported from GitHub
0

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.

Remove background: leave transparent artwork alone, ignore existing transparency, keep ink un-mixed, half the memory

KnifeLemoncde6b44064b5
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 5300e394..5574c844 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -301,9 +301,9 @@
"presets.keep_color_profile_hint": "Available when metadata is removed. Without the colour profile, wide-gamut photos (Display P3 from phones) can look washed out.",
"presets.grayscale": "Grayscale",
"presets.remove_background": "Remove background",
- "presets.remove_background_hint": "Make a plain background transparent: the paper behind a signature or stamp, the backdrop of a logo. Formats without transparency (JPG) get the background colour below instead. Not meant for photos of people or busy scenes.",
+ "presets.remove_background_hint": "Make a plain background transparent: the paper behind a signature or stamp, the backdrop of a logo. The colour along the image edge counts as the background, so leave some paper around the artwork. Formats without transparency (JPG) get the background colour below instead. Not meant for photos of people or busy scenes.",
"presets.background_tolerance": "Background tolerance",
- "presets.background_tolerance_hint": "Higher removes more: paper in shadow, faint smudges. Too high also thins light strokes.",
+ "presets.background_tolerance_hint": "Higher removes more: paper in shadow, faint smudges. Too high also thins light strokes. Light grey areas become see-through; to keep a fill inside an outline, turn on \"Keep enclosed areas\".",
"presets.keep_enclosed_background": "Keep enclosed areas",
"presets.keep_enclosed_background_hint": "Only remove the background connected to the image edge, so the white inside a logo stays. Leave off for handwriting: it would keep the paper inside letters such as \"o\".",
"presets.background": "Background for transparency",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index bafda661..e60b3710 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -301,9 +301,9 @@
"presets.keep_color_profile_hint": "메타데이터를 지울 때 선택할 수 있어요. 색 프로필이 없으면 휴대폰의 Display P3 사진처럼 색 영역이 넓은 사진은 색이 바래 보일 수 있어요.",
"presets.grayscale": "흑백으로",
"presets.remove_background": "배경 제거",
- "presets.remove_background_hint": "서명이나 도장 뒤의 종이, 로고 뒤의 단색 배경을 투명하게 만들어요. 투명을 지원하지 않는 형식(JPG)은 아래 배경색으로 채워져요. 사람 사진이나 복잡한 배경용은 아니에요.",
+ "presets.remove_background_hint": "서명이나 도장 뒤의 종이, 로고 뒤의 단색 배경을 투명하게 만들어요. 이미지 가장자리의 색을 배경으로 보니, 그림 둘레에 종이를 조금 남겨 두세요. 투명을 지원하지 않는 형식(JPG)은 아래 배경색으로 채워져요. 사람 사진이나 복잡한 배경용은 아니에요.",
"presets.background_tolerance": "배경 허용 범위",
- "presets.background_tolerance_hint": "높을수록 그늘진 종이나 옅은 얼룩까지 지워요. 너무 높으면 옅은 획도 가늘어져요.",
+ "presets.background_tolerance_hint": "높을수록 그늘진 종이나 옅은 얼룩까지 지워요. 너무 높으면 옅은 획도 가늘어져요. 연한 회색 면은 반투명해지니, 테두리 안의 면을 남기려면 \"안쪽 영역 유지\"를 켜세요.",
"presets.keep_enclosed_background": "안쪽 영역 유지",
"presets.keep_enclosed_background_hint": "이미지 가장자리와 이어진 배경만 지워서 로고 안쪽의 흰색은 남겨요. 손글씨에는 끄세요. \"o\" 같은 글자 안쪽 종이까지 남아요.",
"presets.background": "투명 영역 배경색",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index ddb2946c..6540f1b5 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -301,9 +301,9 @@
"presets.keep_color_profile_hint": "删除元数据时可选。没有颜色配置文件时,手机拍摄的 Display P3 等广色域照片可能会显得发灰。",
"presets.grayscale": "转为灰度",
"presets.remove_background": "去除背景",
- "presets.remove_background_hint": "将纯色背景变为透明:签名或印章后面的纸张、标志后面的底色。不支持透明的格式(JPG)会改用下方的背景色。不适用于人物照片或复杂场景。",
+ "presets.remove_background_hint": "将纯色背景变为透明:签名或印章后面的纸张、标志后面的底色。图片边缘的颜色会被当作背景,因此请在图案周围留一些纸张。不支持透明的格式(JPG)会改用下方的背景色。不适用于人物照片或复杂场景。",
"presets.background_tolerance": "背景容差",
- "presets.background_tolerance_hint": "越高去除越多:阴影中的纸张、浅色污渍。过高也会让浅色笔画变细。",
+ "presets.background_tolerance_hint": "越高去除越多:阴影中的纸张、浅色污渍。过高也会让浅色笔画变细。浅灰色区域会变成半透明,若要保留轮廓内的填充,请打开“保留封闭区域”。",
"presets.keep_enclosed_background": "保留封闭区域",
"presets.keep_enclosed_background_hint": "只去除与图像边缘相连的背景,标志内部的白色会保留。手写内容请关闭:否则 “o” 等字母内部的纸张也会保留。",
"presets.background": "透明区域背景色",
diff --git a/src/Filee.Engines/Magick/BackgroundRemover.cs b/src/Filee.Engines/Magick/BackgroundRemover.cs
index b8932011..90431b9b 100644
--- a/src/Filee.Engines/Magick/BackgroundRemover.cs
+++ b/src/Filee.Engines/Magick/BackgroundRemover.cs
@@ -39,6 +39,9 @@ public static class BackgroundRemover
/// </summary>
private const float MinHeadroom = 96f;
+ /// <summary>Smallest side of an image whose lone pixels are cleared as noise.</summary>
+ private const int MinSpeckSize = 32;
+
/// <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>
@@ -52,56 +55,65 @@ public static class BackgroundRemover
// CMYK and gray sources are read as RGB so the colour arithmetic below holds.
if (image.ColorSpace is not (ColorSpace.sRGB or ColorSpace.RGB))
image.ColorSpace = ColorSpace.sRGB;
- var pixels = image.GetPixels().ToByteArray(PixelMapping.RGBA);
+ byte[]? pixels;
+ using (var collection = image.GetPixels())
+ pixels = collection.ToByteArray(PixelMapping.RGBA);
if (pixels is null)
return;
if (BorderColor(pixels, width, height) is not { } border)
- return; // the edge is already transparent: nothing to tell the backdrop by
+ return; // the edge is mostly transparent already: nothing to tell the backdrop by
var cutoff = Math.Clamp(tolerance, 0, 100) / 100f * MaxCutoff;
var backdrop = new Backdrop(pixels, width, height, border, tolerance / 100f);
- var count = width * height;
- var raw = new float[count]; // opacity before the thresholds, also used by the edge flood fill
+ // Opacity before the thresholds in 1/255 steps (a byte per pixel keeps a 48-megapixel photo affordable), also
+ // used by the edge flood fill. Pixels that are already transparent count as removed backdrop, not as ink.
+ var raw = new byte[width * height];
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var o = (y * width + x) * 4;
+ if (pixels[o + 3] < 128)
+ continue;
var (br, bg, bb) = backdrop.At(x, y);
- raw[y * width + x] = Math.Max(Opacity(pixels[o], br), Math.Max(Opacity(pixels[o + 1], bg), Opacity(pixels[o + 2], bb)));
+ var opacity = Math.Max(Opacity(pixels[o], br), Math.Max(Opacity(pixels[o + 1], bg), Opacity(pixels[o + 2], bb)));
+ raw[y * width + x] = (byte)Math.Round(Math.Min(opacity, 1f) * 255);
}
}
var full = InkOpacity(raw, cutoff);
+ var enclosed = keepEnclosed ? Enclosed(raw, width, height, (cutoff + full) / 2) : null;
- var result = new byte[pixels.Length];
+ // Written into the pixel array itself: each pixel is read once, right before it is replaced.
for (var y = 0; y < height; y++)
{
for (var x = 0; x < width; x++)
{
var i = y * width + x;
+ if (enclosed?[i] == true)
+ continue; // backdrop inside a closed shape keeps its colour
var o = i * 4;
- var alpha = Math.Clamp((raw[i] - cutoff) / (full - cutoff), 0f, 1f);
+ var alpha = Math.Clamp((raw[i] / 255f - cutoff) / (full - cutoff), 0f, 1f);
if (alpha > 0)
{
// 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);
- result[o] = Unmix(pixels[o], br, alpha);
- result[o + 1] = Unmix(pixels[o + 1], bg, alpha);
- result[o + 2] = Unmix(pixels[o + 2], bb, alpha);
+ 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);
}
- result[o + 3] = (byte)Math.Round(alpha * pixels[o + 3]);
+ pixels[o + 3] = (byte)Math.Round(alpha * pixels[o + 3]);
}
}
- RemoveSpecks(result, width, height);
- if (keepEnclosed)
- RestoreEnclosed(pixels, result, raw, width, height, (cutoff + full) / 2);
+ // Icons and other tiny images have no paper grain, and their single pixels are details.
+ if (width >= MinSpeckSize && height >= MinSpeckSize)
+ RemoveSpecks(pixels, width, height);
image.Alpha(AlphaOption.Set);
- image.ImportPixels(result, new PixelImportSettings((uint)width, (uint)height, StorageType.Char, PixelMapping.RGBA));
+ image.ImportPixels(pixels, new PixelImportSettings((uint)width, (uint)height, StorageType.Char, PixelMapping.RGBA));
}
/// <summary>
@@ -110,16 +122,16 @@ public static class BackgroundRemover
/// anti-aliased edges keep their partial alpha; faint pencil reaches only about 0.4, and its strokes still become
/// solid instead of half transparent.
/// </summary>
- private static float InkOpacity(float[] raw, float cutoff)
+ private static float InkOpacity(byte[] raw, float cutoff)
{
var floor = Math.Min(1f, cutoff + MinSoftBand);
var histogram = new int[256];
var total = 0;
foreach (var a in raw)
{
- if (a < floor)
+ if (a / 255f < floor)
continue;
- histogram[(int)(Math.Min(a, 1f) * 255)]++;
+ histogram[a]++;
total++;
}
if (total == 0)
@@ -144,14 +156,19 @@ public static class BackgroundRemover
private static byte Unmix(byte value, float backdrop, float alpha) =>
(byte)Math.Clamp(Math.Round(backdrop + (value - backdrop) / alpha), 0, 255);
- /// <summary>Per-channel median of the opaque border pixels, or null when the border is transparent.</summary>
+ /// <summary>
+ /// Per-channel median of the opaque border pixels, or null when most of the border is transparent: that image has
+ /// no backdrop left, and the few opaque border pixels would be its own artwork (a logo touching the edge).
+ /// </summary>
private static (float R, float G, float B)? BorderColor(byte[] pixels, int width, int height)
{
var r = new List<byte>();
var g = new List<byte>();
var b = new List<byte>();
+ var all = 0;
void Add(int x, int y)
{
+ all++;
var o = (y * width + x) * 4;
if (pixels[o + 3] < 128)
return;
@@ -169,7 +186,7 @@ public static class BackgroundRemover
Add(0, y);
Add(width - 1, y);
}
- return r.Count == 0 ? null : (Median(r), Median(g), Median(b));
+ return r.Count * 2 < all ? null : (Median(r), Median(g), Median(b));
}
private static float Median(List<byte> values)
@@ -211,16 +228,18 @@ public static class BackgroundRemover
}
/// <summary>
- /// Gives the pixels inside closed shapes back their original colour: removed pixels count only when the removed
- /// area they belong to touches the image edge (4-connected flood fill that stops at pixels at least half opaque).
+ /// The backdrop inside closed shapes, which keeps its colour: backdrop the image edge cannot reach (4-connected
+ /// flood fill that stops at pixels at least <paramref name="wall"/> opaque). Ink is never part of it, so the edges
+ /// of a stroke keep their un-mixed colour and lone specks stay removed.
/// </summary>
- private static void RestoreEnclosed(byte[] source, byte[] result, float[] raw, int width, int height, float wall)
+ private static bool[] Enclosed(byte[] raw, int width, int height, float wall)
{
+ var limit = (byte)Math.Clamp(Math.Round(wall * 255), 0, 255);
var reached = new bool[raw.Length];
var queue = new Queue<int>();
void Visit(int i)
{
- if (!reached[i] && raw[i] < wall)
+ if (!reached[i] && raw[i] < limit)
{
reached[i] = true;
queue.Enqueue(i);
@@ -245,10 +264,8 @@ public static class BackgroundRemover
if (i < raw.Length - width) Visit(i + width);
}
for (var i = 0; i < raw.Length; i++)
- {
- if (!reached[i])
- Array.Copy(source, i * 4, result, i * 4, 4);
- }
+ reached[i] = !reached[i] && raw[i] < limit;
+ return reached;
}
/// <summary>
@@ -276,8 +293,9 @@ public static class BackgroundRemover
_rows = (height + _block - 1) / _block;
if (_columns < 2 && _rows < 2)
return;
- // Higher tolerance accepts deeper shadows; at 0 a light grey area (a smudge, a pale logo) is not paper.
- _darkest = 0.85f - 0.35f * Math.Clamp(tolerance, 0, 1);
+ // Higher tolerance accepts deeper shadows. At the default (25) a light grey fill such as #D0D0D0 (a logo,
+ // table shading) is not taken for paper in shadow; a photo with a deep shadow needs a higher tolerance.
+ _darkest = 0.92f - 0.30f * Math.Clamp(tolerance, 0, 1);
_grid = Estimate(pixels, width, height);
}
diff --git a/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs b/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs
index 6c92b5e9..86b1551c 100644
--- a/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs
+++ b/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs
@@ -112,6 +112,88 @@ public class BackgroundRemovalTests(EngineFixture fx) : IClassFixture<EngineFixt
Assert.True(inside.R > 240, inside.ToString());
}
+ [Fact]
+ public void Transparent_artwork_touching_the_edge_is_left_alone()
+ {
+ // A transparent PNG logo whose blue block touches the left edge: its blue was taken for the backdrop and the
+ // whole image came out empty.
+ using var image = new MagickImage(MagickColors.Transparent, 160, 100);
+ new Drawables().FillColor(new MagickColor("#2F6FD6")).Rectangle(0, 25, 70, 75).Draw(image);
+
+ Removed(image);
+
+ var block = Pixel(image, 30, 50);
+ Assert.Equal(255, block.A);
+ Assert.Equal(0x2F, block.R);
+ }
+
+ [Fact]
+ public void Transparent_pixels_already_there_do_not_count_as_ink()
+ {
+ // Paper with a transparent corner and a grey stroke: the transparent pixels (0,0,0,0) counted as black ink and
+ // turned the stroke into half-transparent black.
+ using var image = new MagickImage(MagickColors.White, 160, 100);
+ new Drawables().StrokeColor(new MagickColor("#555555")).StrokeWidth(6).Line(15, 70, 140, 70).Draw(image);
+ image.Alpha(AlphaOption.Set);
+ using (var pixels = image.GetPixels())
+ for (var y = 0; y < 30; y++)
+ for (var x = 110; x < 160; x++)
+ pixels.SetPixel(x, y, [0, 0, 0, 0]);
+
+ Removed(image);
+
+ var stroke = Pixel(image, 60, 70);
+ Assert.Equal(255, stroke.A);
+ Assert.InRange(stroke.R, 0x50, 0x5A);
+ Assert.Equal(0, Pixel(image, 5, 5).A);
+ }
+
+ [Fact]
+ public void Keep_enclosed_areas_only_keeps_backdrop_and_leaves_ink_un_mixed()
+ {
+ // A dark edge pixel of a stroke (#404040 next to black) is ink: un-mixed to partly transparent black, with or
+ // without "keep enclosed areas", instead of copied back as opaque grey.
+ using var plain = new MagickImage(MagickColors.White, 120, 120);
+ new Drawables().StrokeColor(MagickColors.Black).StrokeWidth(8).FillColor(MagickColors.Transparent)
+ .Rectangle(20, 20, 100, 100).Draw(plain);
+ using (var pixels = plain.GetPixels())
+ pixels.SetPixel(60, 25, [0x40, 0x40, 0x40, 0xFF]);
+ using var kept = (MagickImage)plain.Clone();
+
+ Removed(plain);
+ Removed(kept, keepEnclosed: true);
+
+ Assert.Equal(Pixel(plain, 60, 25).ToString(), Pixel(kept, 60, 25).ToString());
+ Assert.True(Pixel(kept, 60, 25).A < 255);
+ Assert.Equal(255, Pixel(kept, 60, 60).A); // the paper inside the frame stays
+ }
+
+ [Fact]
+ public void A_light_grey_fill_inside_an_outline_stays_with_keep_enclosed_areas()
+ {
+ using var image = new MagickImage(MagickColors.White, 300, 200);
+ new Drawables().StrokeColor(MagickColors.Black).StrokeWidth(4).FillColor(new MagickColor("#D0D0D0"))
+ .Rectangle(60, 40, 240, 160).Draw(image);
+
+ Removed(image, keepEnclosed: true);
+
+ Assert.Equal("#D0D0D0FF", Pixel(image, 150, 100).ToString());
+ Assert.Equal(0, Pixel(image, 10, 10).A);
+ }
+
+ [Fact]
+ public void Single_pixels_of_tiny_images_are_details_not_noise()
+ {
+ using var icon = new MagickImage(MagickColors.White, 3, 3);
+ using (var pixels = icon.GetPixels())
+ pixels.SetPixel(1, 1, [0, 0, 0, 255]);
+
+ Removed(icon);
+
+ Assert.Equal(255, Pixel(icon, 1, 1).A);
+ Assert.Equal(0, Pixel(icon, 0, 0).A);
+ }
+
[Fact]
public void A_dark_backdrop_is_removed_and_light_content_kept()
{