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.

Add simple image background removal

SeoJCalived732df5e3d2b
diff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.json
index 88d45d67..5300e394 100644
--- a/src/Filee.App/Assets/i18n/en.json
+++ b/src/Filee.App/Assets/i18n/en.json
@@ -102,6 +102,7 @@
"preset.half_size": "Half size",
"preset.grayscale": "Grayscale",
+ "preset.remove_background": "Remove background",
"preset.merge_pdf": "Merge PDF",
"preset.split_pdf": "Split PDF",
"preset.long_image": "Long image",
@@ -299,6 +300,12 @@
"presets.keep_color_profile": "Keep colour profile (ICC)",
"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.background_tolerance": "Background tolerance",
+ "presets.background_tolerance_hint": "Higher removes more: paper in shadow, faint smudges. Too high also thins light strokes.",
+ "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",
"presets.tiff_compression": "TIFF compression",
"presets.webp_lossless": "Lossless WEBP",
diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.json
index 706176bf..bafda661 100644
--- a/src/Filee.App/Assets/i18n/ko.json
+++ b/src/Filee.App/Assets/i18n/ko.json
@@ -102,6 +102,7 @@
"preset.half_size": "50% 축소",
"preset.grayscale": "흑백",
+ "preset.remove_background": "배경 제거",
"preset.merge_pdf": "PDF 병합",
"preset.split_pdf": "PDF 분할",
"preset.long_image": "긴 이미지",
@@ -299,6 +300,12 @@
"presets.keep_color_profile": "색 프로필 유지 (ICC)",
"presets.keep_color_profile_hint": "메타데이터를 지울 때 선택할 수 있어요. 색 프로필이 없으면 휴대폰의 Display P3 사진처럼 색 영역이 넓은 사진은 색이 바래 보일 수 있어요.",
"presets.grayscale": "흑백으로",
+ "presets.remove_background": "배경 제거",
+ "presets.remove_background_hint": "서명이나 도장 뒤의 종이, 로고 뒤의 단색 배경을 투명하게 만들어요. 투명을 지원하지 않는 형식(JPG)은 아래 배경색으로 채워져요. 사람 사진이나 복잡한 배경용은 아니에요.",
+ "presets.background_tolerance": "배경 허용 범위",
+ "presets.background_tolerance_hint": "높을수록 그늘진 종이나 옅은 얼룩까지 지워요. 너무 높으면 옅은 획도 가늘어져요.",
+ "presets.keep_enclosed_background": "안쪽 영역 유지",
+ "presets.keep_enclosed_background_hint": "이미지 가장자리와 이어진 배경만 지워서 로고 안쪽의 흰색은 남겨요. 손글씨에는 끄세요. \"o\" 같은 글자 안쪽 종이까지 남아요.",
"presets.background": "투명 영역 배경색",
"presets.tiff_compression": "TIFF 압축",
"presets.webp_lossless": "무손실 WEBP",
diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.json
index 7958d029..ddb2946c 100644
--- a/src/Filee.App/Assets/i18n/zh-CN.json
+++ b/src/Filee.App/Assets/i18n/zh-CN.json
@@ -102,6 +102,7 @@
"preset.half_size": "缩小 50%",
"preset.grayscale": "灰度",
+ "preset.remove_background": "去除背景",
"preset.merge_pdf": "合并 PDF",
"preset.split_pdf": "拆分 PDF",
"preset.long_image": "长图",
@@ -299,6 +300,12 @@
"presets.keep_color_profile": "保留颜色配置文件 (ICC)",
"presets.keep_color_profile_hint": "删除元数据时可选。没有颜色配置文件时,手机拍摄的 Display P3 等广色域照片可能会显得发灰。",
"presets.grayscale": "转为灰度",
+ "presets.remove_background": "去除背景",
+ "presets.remove_background_hint": "将纯色背景变为透明:签名或印章后面的纸张、标志后面的底色。不支持透明的格式(JPG)会改用下方的背景色。不适用于人物照片或复杂场景。",
+ "presets.background_tolerance": "背景容差",
+ "presets.background_tolerance_hint": "越高去除越多:阴影中的纸张、浅色污渍。过高也会让浅色笔画变细。",
+ "presets.keep_enclosed_background": "保留封闭区域",
+ "presets.keep_enclosed_background_hint": "只去除与图像边缘相连的背景,标志内部的白色会保留。手写内容请关闭:否则 “o” 等字母内部的纸张也会保留。",
"presets.background": "透明区域背景色",
"presets.tiff_compression": "TIFF 压缩",
"presets.webp_lossless": "无损 WEBP",
diff --git a/src/Filee.App/ViewModels/PresetEditorViewModel.cs b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
index 1e61ab63..b608376d 100644
--- a/src/Filee.App/ViewModels/PresetEditorViewModel.cs
+++ b/src/Filee.App/ViewModels/PresetEditorViewModel.cs
@@ -98,6 +98,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
_keepMetadata = _edit.Image.KeepMetadata;
_keepColorProfile = _edit.Image.KeepColorProfile;
_grayscale = _edit.Image.Grayscale;
+ _removeBackground = _edit.Image.RemoveBackground;
+ _backgroundTolerance = _edit.Image.BackgroundTolerance;
+ _keepEnclosedBackground = _edit.Image.KeepEnclosedBackground;
_background = _edit.Image.Background;
_webpLossless = _edit.Image.WebpLossless;
_multiPageTiff = _edit.Image.MultiPageTiff;
@@ -184,6 +187,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
}
}
[ObservableProperty] private bool _grayscale;
+ [ObservableProperty] private bool _removeBackground;
+ [ObservableProperty] private int _backgroundTolerance;
+ [ObservableProperty] private bool _keepEnclosedBackground;
[ObservableProperty] private string _background;
[ObservableProperty] private bool _webpLossless;
[ObservableProperty] private bool _multiPageTiff;
@@ -278,6 +284,9 @@ public sealed partial class PresetEditorViewModel : ObservableObject
image.KeepMetadata = KeepMetadata;
image.KeepColorProfile = KeepColorProfile;
image.Grayscale = Grayscale;
+ image.RemoveBackground = RemoveBackground;
+ image.BackgroundTolerance = Math.Clamp(BackgroundTolerance, 0, 100);
+ image.KeepEnclosedBackground = KeepEnclosedBackground;
image.Background = string.IsNullOrWhiteSpace(Background) ? "#FFFFFF" : Background.Trim();
image.TiffCompression = TiffCompression.Value;
image.WebpLossless = WebpLossless;
diff --git a/src/Filee.App/Views/PresetEditorView.axaml b/src/Filee.App/Views/PresetEditorView.axaml
index 19447e9c..4f6ae7b9 100644
--- a/src/Filee.App/Views/PresetEditorView.axaml
+++ b/src/Filee.App/Views/PresetEditorView.axaml
@@ -77,6 +77,18 @@
<CheckBox Content="{DynamicResource presets.grayscale}" IsChecked="{Binding Grayscale}" Margin="0,0,18,0" />
<CheckBox Content="{DynamicResource presets.webp_lossless}" IsChecked="{Binding WebpLossless}" IsVisible="{Binding ShowWebp}" />
</WrapPanel>
+ <CheckBox Content="{DynamicResource presets.remove_background}" IsChecked="{Binding RemoveBackground}"
+ ToolTip.Tip="{DynamicResource presets.remove_background_hint}" />
+ <StackPanel Spacing="6" IsVisible="{Binding RemoveBackground}">
+ <DockPanel>
+ <TextBlock DockPanel.Dock="Right" Text="{Binding BackgroundTolerance}" FontWeight="SemiBold" />
+ <TextBlock Classes="label" Text="{DynamicResource presets.background_tolerance}" />
+ </DockPanel>
+ <Slider Minimum="0" Maximum="100" Value="{Binding BackgroundTolerance}" TickFrequency="1" IsSnapToTickEnabled="True"
+ ToolTip.Tip="{DynamicResource presets.background_tolerance_hint}" />
+ <CheckBox Content="{DynamicResource presets.keep_enclosed_background}" IsChecked="{Binding KeepEnclosedBackground}"
+ ToolTip.Tip="{DynamicResource presets.keep_enclosed_background_hint}" />
+ </StackPanel>
<Grid ColumnDefinitions="*,12,*">
<StackPanel>
<TextBlock Classes="label" Text="{DynamicResource presets.background}" />
diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.cs
index f2f5aeba..b40fe897 100644
--- a/src/Filee.Core/Presets/BuiltInData.cs
+++ b/src/Filee.Core/Presets/BuiltInData.cs
@@ -39,6 +39,11 @@ public static class BuiltInData
Image = { Grayscale = true }, Output = { FileNamePattern = "{name}_gray" },
},
new()
+ {
+ Id = "remove-background", NameKey = "preset.remove_background", TargetFormat = "png",
+ Image = { RemoveBackground = true }, Output = { FileNamePattern = "{name}_transparent" },
+ },
+ new()
{
Id = "tiff-300", Name = "TIFF 300dpi", TargetFormat = "tiff",
Image = { Dpi = 300 }, Pdf = { RenderDpi = 300 }, Output = { FileNamePattern = "{name}_300dpi" },
@@ -167,7 +172,7 @@ public static class BuiltInData
{
Id = "images", NameKey = "profile.images",
Extensions = ExtensionsOf(FormatCategory.Image),
- PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "to-tiff", "to-bmp", "to-ico", "half-size"],
+ PresetIds = ["to-png", "to-jpg", "to-webp", "to-pdf", "to-tiff", "to-bmp", "to-ico", "half-size", "remove-background"],
},
new()
{
diff --git a/src/Filee.Core/Presets/Preset.cs b/src/Filee.Core/Presets/Preset.cs
index 497ad947..8ef81e8a 100644
--- a/src/Filee.Core/Presets/Preset.cs
+++ b/src/Filee.Core/Presets/Preset.cs
@@ -113,6 +113,21 @@ public sealed class ImageOptions
/// <summary>Convert to grayscale.</summary>
public bool Grayscale { get; set; }
+ /// <summary>
+ /// Make a plain background (paper behind a signature or stamp, the backdrop of a logo) transparent. Targets without
+ /// an alpha channel get <see cref="Background"/> instead, so this also replaces the backdrop colour.
+ /// </summary>
+ public bool RemoveBackground { get; set; }
+
+ /// <summary>0-100: how different from the backdrop a pixel may be and still be removed (<see cref="RemoveBackground"/>).</summary>
+ public int BackgroundTolerance { get; set; } = 25;
+
+ /// <summary>
+ /// With <see cref="RemoveBackground"/>: only remove the backdrop connected to the image edge, keeping enclosed
+ /// areas such as the white inside a logo. Off by default: it also keeps the paper inside handwritten loops.
+ /// </summary>
+ public bool KeepEnclosedBackground { get; set; }
+
/// <summary>Fill colour for transparent pixels when the target has no alpha channel (e.g. JPG).</summary>
public string Background { get; set; } = "#FFFFFF";
diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.cs
index 5db5dcfc..7e4f98ea 100644
--- a/src/Filee.Core/Settings/AppSettings.cs
+++ b/src/Filee.Core/Settings/AppSettings.cs
@@ -50,7 +50,7 @@ public sealed class DonutSettings
public sealed class AppSettings
{
/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>
- public const int CurrentSchemaVersion = 9;
+ public const int CurrentSchemaVersion = 10;
public int SchemaVersion { get; set; } = CurrentSchemaVersion;
diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.cs
index e3791a88..27c55786 100644
--- a/src/Filee.Core/Settings/UserDataStore.cs
+++ b/src/Filee.Core/Settings/UserDataStore.cs
@@ -352,6 +352,14 @@ internal static class SettingsMigrations
}
changed |= Offer(presets, profiles, "pdf", "pdf-long-image", "to-jpg");
}
+
+ // v10: "Remove background" (signatures, stamps, logos → transparent PNG), on the image donut after "half size".
+ if (from < 10 && presets.All(p => p.Id != "remove-background"))
+ {
+ presets.Add(BuiltInData.CreatePresets().Single(p => p.Id == "remove-background"));
+ Offer(presets, profiles, "images", "remove-background", "half-size");
+ changed = true;
+ }
return changed;
}
diff --git a/src/Filee.Engines/Magick/BackgroundRemover.cs b/src/Filee.Engines/Magick/BackgroundRemover.cs
new file mode 100644
index 00000000..b8932011
--- /dev/null
+++ b/src/Filee.Engines/Magick/BackgroundRemover.cs
@@ -0,0 +1,395 @@
+// Simple background removal: turns the paper or plain backdrop of signatures, stamps, logos and scans transparent.
+// No model and no network: the backdrop colour is estimated region by region, and every pixel is "un-mixed" from it.
+
+using ImageMagick;
+
+namespace Filee.Engines.Magick;
+
+/// <summary>
+/// Makes a plain (single-colour) background transparent. Built for signatures, stamps and logos on paper or a flat
+/// backdrop; photos of people, hair or busy scenes need a segmentation model and are out of scope.
+/// </summary>
+/// <remarks>
+/// <para>
+/// 1. The backdrop colour is the per-channel median of the border pixels, which shrugs off ink touching the edge and
+/// JPEG noise. 2. A light backdrop is then estimated again per block, so a shadow or a lamp's falloff across a phone
+/// photo of paper is removed as well; a block only counts pixels that are a brighter or darker shade of the border
+/// 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.
+/// </para>
+/// <para>
+/// Optionally only the backdrop reachable from the image edge is removed, so the white inside a logo stays. This is
+/// off by default because it would also keep the paper inside the loops of handwriting ("o", "a", "e").
+/// </para>
+/// </remarks>
+public static class BackgroundRemover
+{
+ /// <summary>Opacity below which a pixel is fully removed at tolerance 100 (it scales linearly from 0).</summary>
+ private const float MaxCutoff = 0.48f;
+
+ /// <summary>Narrowest band between fully removed and fully kept, in opacity.</summary>
+ private const float MinSoftBand = 0.15f;
+
+ /// <summary>
+ /// Smallest headroom between the backdrop and black or white used for the opacity. Without it, noise on nearly
+ /// white paper (250 → 255) would count as fully opaque white ink.
+ /// </summary>
+ private const float MinHeadroom = 96f;
+
+ /// <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>
+ public static void Apply(IMagickImage<byte> image, int tolerance, bool keepEnclosed)
+ {
+ var width = (int)image.Width;
+ var height = (int)image.Height;
+ if (width < 2 || height < 2)
+ return;
+
+ // 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);
+ 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
+
+ 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
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ var o = (y * width + x) * 4;
+ 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 full = InkOpacity(raw, cutoff);
+
+ var result = new byte[pixels.Length];
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ var i = y * width + x;
+ var o = i * 4;
+ var alpha = Math.Clamp((raw[i] - 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);
+ }
+ result[o + 3] = (byte)Math.Round(alpha * pixels[o + 3]);
+ }
+ }
+
+ RemoveSpecks(result, width, height);
+ if (keepEnclosed)
+ RestoreEnclosed(pixels, result, raw, width, height, (cutoff + full) / 2);
+
+ image.Alpha(AlphaOption.Set);
+ image.ImportPixels(result, new PixelImportSettings((uint)width, (uint)height, StorageType.Char, PixelMapping.RGBA));
+ }
+
+ /// <summary>
+ /// The raw opacity that counts as fully opaque: that of the ink itself (75th percentile of the clearly visible
+ /// pixels, so the core of a stroke is solid and only its edges are not). Black ink reaches about 0.9 and its
+ /// 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)
+ {
+ var floor = Math.Min(1f, cutoff + MinSoftBand);
+ var histogram = new int[256];
+ var total = 0;
+ foreach (var a in raw)
+ {
+ if (a < floor)
+ continue;
+ histogram[(int)(Math.Min(a, 1f) * 255)]++;
+ total++;
+ }
+ if (total == 0)
+ return floor;
+ var seen = 0;
+ for (var bin = 0; bin < histogram.Length; bin++)
+ {
+ seen += histogram[bin];
+ if (seen * 4 >= total * 3)
+ return Math.Max(floor, bin / 255f);
+ }
+ return 1f;
+ }
+
+ /// <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)
+ {
+ var d = value - backdrop;
+ return d >= 0 ? d / Math.Max(255f - backdrop, MinHeadroom) : -d / Math.Max(backdrop, MinHeadroom);
+ }
+
+ 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>
+ 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>();
+ void Add(int x, int y)
+ {
+ var o = (y * width + x) * 4;
+ if (pixels[o + 3] < 128)
+ return;
+ r.Add(pixels[o]);
+ g.Add(pixels[o + 1]);
+ b.Add(pixels[o + 2]);
+ }
+ for (var x = 0; x < width; x++)
+ {
+ Add(x, 0);
+ Add(x, height - 1);
+ }
+ for (var y = 1; y < height - 1; y++)
+ {
+ Add(0, y);
+ Add(width - 1, y);
+ }
+ return r.Count == 0 ? null : (Median(r), Median(g), Median(b));
+ }
+
+ private static float Median(List<byte> values)
+ {
+ values.Sort();
+ return values[values.Count / 2];
+ }
+
+ /// <summary>
+ /// Clears lone visible pixels (sensor noise, paper grain, dust) that have at most one visible neighbour. Strokes
+ /// are at least a line of pixels, so every pixel of one has two neighbours or more.
+ /// </summary>
+ private static void RemoveSpecks(byte[] result, int width, int height)
+ {
+ var specks = new List<int>();
+ for (var y = 0; y < height; y++)
+ {
+ for (var x = 0; x < width; x++)
+ {
+ if (result[(y * width + x) * 4 + 3] == 0)
+ continue;
+ var neighbours = 0;
+ for (var dy = -1; dy <= 1; dy++)
+ {
+ for (var dx = -1; dx <= 1; dx++)
+ {
+ int nx = x + dx, ny = y + dy;
+ if ((dx != 0 || dy != 0) && nx >= 0 && nx < width && ny >= 0 && ny < height
+ && result[(ny * width + nx) * 4 + 3] != 0)
+ neighbours++;
+ }
+ }
+ if (neighbours <= 1)
+ specks.Add(y * width + x);
+ }
+ }
+ foreach (var i in specks)
+ result[i * 4 + 3] = 0;
+ }
+
+ /// <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).
+ /// </summary>
+ private static void RestoreEnclosed(byte[] source, byte[] result, float[] raw, int width, int height, float wall)
+ {
+ var reached = new bool[raw.Length];
+ var queue = new Queue<int>();
+ void Visit(int i)
+ {
+ if (!reached[i] && raw[i] < wall)
+ {
+ reached[i] = true;
+ queue.Enqueue(i);
+ }
+ }
+ for (var x = 0; x < width; x++)
+ {
+ Visit(x);
+ Visit((height - 1) * width + x);
+ }
+ for (var y = 0; y < height; y++)
+ {
+ Visit(y * width);
+ Visit(y * width + width - 1);
+ }
+ while (queue.TryDequeue(out var i))
+ {
+ var x = i % width;
+ if (x > 0) Visit(i - 1);
+ if (x < width - 1) Visit(i + 1);
+ if (i >= width) Visit(i - width);
+ 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);
+ }
+ }
+
+ /// <summary>
+ /// The backdrop colour at each pixel: the border colour, corrected block by block for uneven lighting when the
+ /// backdrop is light (paper). Blocks with too little backdrop (dense ink) borrow from their neighbours.
+ /// </summary>
+ private sealed class Backdrop
+ {
+ /// <summary>Blocks along the longer side.</summary>
+ private const int Blocks = 48;
+
+ private readonly (float R, float G, float B) _border;
+ private readonly (float R, float G, float B)[]? _grid;
+ private readonly int _block, _columns, _rows;
+ private readonly float _darkest;
+
+ public Backdrop(byte[] pixels, int width, int height, (float R, float G, float B) border, float tolerance)
+ {
+ _border = border;
+ // Dark or coloured backdrops are rarely lit unevenly, and "a shade of" a near-black colour is mostly noise.
+ if (Luma(border) < 96)
+ return;
+ _block = Math.Max(8, (int)Math.Ceiling(Math.Max(width, height) / (double)Blocks));
+ _columns = (width + _block - 1) / _block;
+ _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);
+ _grid = Estimate(pixels, width, height);
+ }
+
+ public (float R, float G, float B) At(int x, int y)
+ {
+ if (_grid is null)
+ return _border;
+ // Bilinear between block centres.
+ var fx = Math.Clamp((x + 0.5f) / _block - 0.5f, 0, _columns - 1);
+ var fy = Math.Clamp((y + 0.5f) / _block - 0.5f, 0, _rows - 1);
+ int x0 = (int)fx, y0 = (int)fy;
+ int x1 = Math.Min(x0 + 1, _columns - 1), y1 = Math.Min(y0 + 1, _rows - 1);
+ float tx = fx - x0, ty = fy - y0;
+ var a = _grid[y0 * _columns + x0];
+ var b = _grid[y0 * _columns + x1];
+ var c = _grid[y1 * _columns + x0];
+ var d = _grid[y1 * _columns + x1];
+ float Mix(float p, float q, float s, float t) =>
+ (p * (1 - tx) + q * tx) * (1 - ty) + (s * (1 - tx) + t * tx) * ty;
+ return (Mix(a.R, b.R, c.R, d.R), Mix(a.G, b.G, c.G, d.G), Mix(a.B, b.B, c.B, d.B));
+ }
+
+ private static float Luma((float R, float G, float B) c) => 0.299f * c.R + 0.587f * c.G + 0.114f * c.B;
+
+ private (float R, float G, float B)[] Estimate(byte[] pixels, int width, int height)
+ {
+ var grid = new (float R, float G, float B)?[_columns * _rows];
+ var dot = _border.R * _border.R + _border.G * _border.G + _border.B * _border.B;
+ var r = new List<byte>();
+ var g = new List<byte>();
+ var b = new List<byte>();
+ for (var row = 0; row < _rows; row++)
+ {
+ for (var column = 0; column < _columns; column++)
+ {
+ r.Clear();
+ g.Clear();
+ b.Clear();
+ var total = 0;
+ var yEnd = Math.Min(height, (row + 1) * _block);
+ var xEnd = Math.Min(width, (column + 1) * _block);
+ for (var y = row * _block; y < yEnd; y++)
+ {
+ for (var x = column * _block; x < xEnd; x++)
+ {
+ total++;
+ var o = (y * width + x) * 4;
+ if (pixels[o + 3] < 128)
+ continue;
+ float pr = pixels[o], pg = pixels[o + 1], pb = pixels[o + 2];
+ // A shade of the border colour: k × border, with k from a shadow to a highlight. The border
+ // can itself lie in shadow, so the centre of the sheet may be much brighter than its median.
+ var k = (pr * _border.R + pg * _border.G + pb * _border.B) / dot;
+ if (k < _darkest || k > 1.6f)
+ continue;
+ var off = Math.Max(Math.Abs(pr - k * _border.R), Math.Max(Math.Abs(pg - k * _border.G), Math.Abs(pb - k * _border.B)));
+ if (off > 20)
+ continue;
+ r.Add(pixels[o]);
+ g.Add(pixels[o + 1]);
+ b.Add(pixels[o + 2]);
+ }
+ }
+ // Mostly ink: the median would drift towards the ink, so let the neighbours decide.
+ if (r.Count * 5 >= total * 2)
+ grid[row * _columns + column] = (Median(r), Median(g), Median(b));
+ }
+ }
+ return Smooth(Fill(grid));
+ }
+
+ /// <summary>Gives blocks without an estimate the average of their estimated neighbours, ring by ring.</summary>
+ private (float R, float G, float B)[] Fill((float R, float G, float B)?[] grid)
+ {
+ if (grid.All(c => c is null))
+ return Enumerable.Repeat(_border, grid.Length).ToArray();
+ while (grid.Any(c => c is null))
+ {
+ var next = ((float R, float G, float B)?[])grid.Clone();
+ for (var i = 0; i < grid.Length; i++)
+ {
+ if (grid[i] is not null)
+ continue;
+ var known = Neighbours(i).Select(n => grid[n]).OfType<(float R, float G, float B)>().ToList();
+ if (known.Count > 0)
+ next[i] = (known.Average(c => c.R), known.Average(c => c.G), known.Average(c => c.B));
+ }
+ grid = next;
+ }
+ return grid.Select(c => c!.Value).ToArray();
+ }
+
+ /// <summary>One 3 × 3 box blur, so a single odd block does not leave a visible patch.</summary>
+ private (float R, float G, float B)[] Smooth((float R, float G, float B)[] grid) =>
+ Enumerable.Range(0, grid.Length).Select(i =>
+ {
+ var all = Neighbours(i).Append(i).Select(n => grid[n]).ToList();
+ return (all.Average(c => c.R), all.Average(c => c.G), all.Average(c => c.B));
+ }).ToArray();
+
+ private IEnumerable<int> Neighbours(int i)
+ {
+ int column = i % _columns, row = i / _columns;
+ for (var dy = -1; dy <= 1; dy++)
+ {
+ for (var dx = -1; dx <= 1; dx++)
+ {
+ int c = column + dx, r = row + dy;
+ if ((dx != 0 || dy != 0) && c >= 0 && c < _columns && r >= 0 && r < _rows)
+ yield return r * _columns + c;
+ }
+ }
+ }
+ }
+}
diff --git a/src/Filee.Engines/Magick/ImageEncoder.cs b/src/Filee.Engines/Magick/ImageEncoder.cs
index ff29b026..574820af 100644
--- a/src/Filee.Engines/Magick/ImageEncoder.cs
+++ b/src/Filee.Engines/Magick/ImageEncoder.cs
@@ -180,6 +180,10 @@ internal static class ImageEncoder
}
FitFormat(image, targetFormat);
+ // Before grayscale (a blue signature stays blue until then) and before alpha is flattened for JPG and co.
+ if (options.RemoveBackground)
+ BackgroundRemover.Apply(image, options.BackgroundTolerance, options.KeepEnclosedBackground);
+
if (options.Grayscale)
image.Grayscale();
diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.cs
index 7168c429..d053ccb1 100644
--- a/tests/Filee.App.Tests/RenderTests.cs
+++ b/tests/Filee.App.Tests/RenderTests.cs
@@ -355,7 +355,7 @@ public class RenderTests
window.DonutControl.SetExternalHighlight(1);
Pump();
- Assert.Equal(8, vm.Items.Count);
+ Assert.Equal(9, vm.Items.Count); // the image donut includes "Remove background"
Assert.Equal("JPG 3개", vm.CenterTitle);
Save(window, "donut-images-ko.png");
window.Close();
@@ -432,6 +432,29 @@ public class RenderTests
window.Close();
}
+ [AvaloniaFact]
+ public void Preset_editor_shows_and_saves_background_removal()
+ {
+ TestServices.EnsureInitialized("ko");
+ var preset = Filee.Core.Presets.BuiltInData.CreatePresets().Single(p => p.Id == "remove-background");
+ var vm = new PresetEditorViewModel(preset, AppHost.Get<Filee.Core.Localization.ILocalizer>());
+ Assert.True(vm.RemoveBackground);
+ Assert.Equal(25, vm.BackgroundTolerance);
+ var window = new PresetEditorWindow { DataContext = vm, Height = 900 };
+ window.Show();
+ Pump();
+ Save(window, "preset-remove-background-ko.png");
+ window.Close();
+
+ vm.BackgroundTolerance = 140; // out of range: clamped
+ vm.KeepEnclosedBackground = true;
+ Assert.True(vm.Apply());
+
+ Assert.True(preset.Image.RemoveBackground);
+ Assert.Equal(100, preset.Image.BackgroundTolerance);
+ Assert.True(preset.Image.KeepEnclosedBackground);
+ }
+
[AvaloniaTheory]
[InlineData("en")]
[InlineData("ko")]
diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.cs
index fc091c1a..2408aa77 100644
--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs
+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs
@@ -193,6 +193,25 @@ public class UserDataStoreTests
Assert.False(SettingsMigrations.ApplyToLibrary(8, presets, profiles)); // once only
}
+ [Fact]
+ public void Version_9_libraries_get_remove_background_after_half_size()
+ {
+ // As written by 1.10.x: no "Remove background" preset, and the image donut without it.
+ var presets = BuiltInData.CreatePresets();
+ presets.RemoveAll(p => p.Id == "remove-background");
+ var profiles = BuiltInData.CreateProfiles();
+ var images = profiles.Single(p => p.Id == "images");
+ images.PresetIds.Remove("remove-background");
+
+ Assert.True(SettingsMigrations.ApplyToLibrary(9, presets, profiles));
+
+ var preset = presets.Single(p => p.Id == "remove-background");
+ Assert.True(preset.Image.RemoveBackground);
+ Assert.Equal("png", preset.TargetFormat);
+ Assert.Equal(images.PresetIds.IndexOf("half-size") + 1, images.PresetIds.IndexOf("remove-background"));
+ Assert.False(SettingsMigrations.ApplyToLibrary(9, presets, profiles)); // once only
+ }
+
[Fact]
public void Catalog_migration_ignores_extensions_checked_on_mixed_profiles()
{
diff --git a/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs b/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs
new file mode 100644
index 00000000..6c92b5e9
--- /dev/null
+++ b/tests/Filee.Engines.Tests/BackgroundRemovalTests.cs
@@ -0,0 +1,219 @@
+// "Remove background": signatures, stamps and logos on paper or a plain backdrop become transparent PNGs.
+
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Magick;
+using ImageMagick;
+using ImageMagick.Drawing;
+
+namespace Filee.Engines.Tests;
+
+public class BackgroundRemovalTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ private static IMagickColor<byte> Pixel(IMagickImage<byte> image, int x, int y) =>
+ image.GetPixels().GetPixel(x, y).ToColor()!;
+
+ /// <summary>A "signature": a thick stroke and a ring (an "o") in <paramref name="ink"/> on <paramref name="paper"/>.</summary>
+ private static MagickImage Signature(string paper, string ink)
+ {
+ var image = new MagickImage(new MagickColor(paper), 200, 120);
+ new Drawables()
+ .StrokeColor(new MagickColor(ink)).StrokeWidth(6).FillColor(MagickColors.Transparent)
+ .Line(20, 60, 100, 60)
+ .Circle(150, 60, 150, 85)
+ .Draw(image);
+ return image;
+ }
+
+ private static MagickImage Removed(MagickImage image, int tolerance = 25, bool keepEnclosed = false)
+ {
+ BackgroundRemover.Apply(image, tolerance, keepEnclosed);
+ return image;
+ }
+
+ [Fact]
+ public void Paper_becomes_transparent_and_black_ink_stays_opaque()
+ {
+ using var image = Removed(Signature("white", "black"));
+
+ Assert.True(image.HasAlpha);
+ Assert.Equal(0, Pixel(image, 5, 5).A); // paper
+ Assert.Equal(0, Pixel(image, 150, 60).A); // paper inside the ring
+ var ink = Pixel(image, 60, 60);
+ Assert.Equal(255, ink.A);
+ Assert.True(ink.R < 40 && ink.G < 40 && ink.B < 40, ink.ToString());
+ }
+
+ [Theory]
+ [InlineData("#1E3CB4")] // ballpoint blue
+ [InlineData("#C8282D")] // stamp red
+ public void Coloured_ink_keeps_its_colour(string inkColor)
+ {
+ using var image = Removed(Signature("white", inkColor));
+
+ var expected = new MagickColor(inkColor);
+ var ink = Pixel(image, 60, 60);
+ Assert.Equal(255, ink.A);
+ Assert.InRange(ink.R, expected.R - 8, expected.R + 8);
+ Assert.InRange(ink.G, expected.G - 8, expected.G + 8);
+ Assert.InRange(ink.B, expected.B - 8, expected.B + 8);
+ Assert.Equal(0, Pixel(image, 5, 5).A);
+ }
+
+ [Fact]
+ public void Yellowish_paper_is_removed_too()
+ {
+ using var image = Removed(Signature("#F2EAD3", "black"));
+
+ Assert.Equal(0, Pixel(image, 5, 5).A);
+ Assert.Equal(0, Pixel(image, 100, 100).A);
+ Assert.Equal(255, Pixel(image, 60, 60).A);
+ }
+
+ [Fact]
+ public void Uneven_lighting_across_the_paper_is_removed()
+ {
+ // A phone photo: the paper darkens from white on the left to a shadowed grey on the right.
+ using var image = new MagickImage("gradient:white-#C8C8C8", 120, 300);
+ image.Rotate(-90); // left to right
+ new Drawables().StrokeColor(MagickColors.Black).StrokeWidth(6).Line(30, 60, 270, 60).Draw(image);
+
+ Removed(image);
+
+ foreach (var x in new[] { 5, 100, 200, 295 })
+ Assert.True(Pixel(image, x, 100).A < 10, $"paper at x={x}: alpha {Pixel(image, x, 100).A}");
+ foreach (var x in new[] { 40, 150, 260 })
+ Assert.Equal(255, Pixel(image, x, 60).A);
+ }
+
+ [Fact]
+ public void Anti_aliased_edges_are_un_mixed_instead_of_left_as_a_light_fringe()
+ {
+ // Paper | 50 % grey (a half-covered edge pixel of black ink) | black ink.
+ using var image = new MagickImage(MagickColors.White, 60, 20);
+ new Drawables().FillColor(new MagickColor("#808080")).Rectangle(20, 0, 29, 19)
+ .FillColor(MagickColors.Black).Rectangle(30, 0, 39, 19).Draw(image);
+
+ Removed(image);
+
+ var edge = Pixel(image, 25, 10);
+ Assert.InRange((int)edge.A, 64, 200); // partly transparent ...
+ Assert.True(edge.R < 64, edge.ToString()); // ... and black, not grey
+ }
+
+ [Fact]
+ public void Keep_enclosed_areas_leaves_the_inside_of_a_shape()
+ {
+ using var image = Removed(Signature("white", "black"), keepEnclosed: true);
+
+ Assert.Equal(0, Pixel(image, 5, 5).A);
+ var inside = Pixel(image, 150, 60);
+ Assert.Equal(255, inside.A);
+ Assert.True(inside.R > 240, inside.ToString());
+ }
+
+ [Fact]
+ public void A_dark_backdrop_is_removed_and_light_content_kept()
+ {
+ using var image = Removed(Signature("#101010", "white"));
+
+ Assert.Equal(0, Pixel(image, 5, 5).A);
+ var ink = Pixel(image, 60, 60);
+ Assert.Equal(255, ink.A);
+ Assert.True(ink.R > 230, ink.ToString());
+ }
+
+ [Fact]
+ public void Grayscale_and_cmyk_sources_work()
+ {
+ using var gray = Signature("white", "black");
+ gray.ColorType = ColorType.Grayscale;
+ using var cmyk = Signature("white", "#1E3CB4");
+ cmyk.ColorSpace = ColorSpace.CMYK;
+
+ foreach (var image in new[] { gray, cmyk })
+ {
+ Removed(image);
+ Assert.Equal(0, Pixel(image, 5, 5).A);
+ Assert.Equal(255, Pixel(image, 60, 60).A);
+ }
+ }
+
+ [Fact]
+ public void Higher_tolerance_removes_faint_smudges()
+ {
+ // A faint grey smudge (a fold or eraser mark) next to real ink.
+ using var low = new MagickImage(MagickColors.White, 120, 60);
+ new Drawables().FillColor(new MagickColor("#C8C8C8")).Rectangle(10, 10, 40, 50)
+ .FillColor(MagickColors.Black).Rectangle(70, 10, 100, 50).Draw(low);
+ using var high = (MagickImage)low.Clone();
+
+ Removed(low, tolerance: 0);
+ Removed(high, tolerance: 100);
+
+ Assert.True(Pixel(low, 25, 30).A > 0);
+ Assert.Equal(0, Pixel(high, 25, 30).A);
+ Assert.Equal(255, Pixel(high, 85, 30).A);
+ }
+
+ [Fact]
+ public async Task Jpg_signature_becomes_a_transparent_png_with_the_built_in_preset()
+ {
+ var dir = fx.NewFolder();
+ var source = Path.Combine(dir, "signature.jpg");
+ using (var image = Signature("white", "#1E3CB4"))
+ {
+ image.Quality = 85;
+ image.Write(source, MagickFormat.Jpg);
+ }
+ var preset = BuiltInData.CreatePresets().Single(p => p.Id == "remove-background");
+
+ var job = await fx.ConvertAsync([source], preset);
+
+ Assert.Equal(JobState.Completed, job.State);
+ var output = job.Outputs.Single();
+ Assert.Equal("signature_transparent.png", Path.GetFileName(output));
+ using var result = new MagickImage(output);
+ Assert.Equal(MagickFormat.Png, result.Format);
+ Assert.True(result.HasAlpha);
+ Assert.Equal(0, Pixel(result, 5, 5).A); // JPEG noise on the paper is gone as well
+ Assert.Equal(0, Pixel(result, 100, 110).A);
+ Assert.Equal(255, Pixel(result, 60, 60).A);
+ }
+
+ [Fact]
+ public async Task Jpg_target_gets_the_background_colour_instead_of_transparency()
+ {
+ var dir = fx.NewFolder();
+ var source = Path.Combine(dir, "logo.png");
+ using (var image = Signature("white", "black"))
+ image.Write(source, MagickFormat.Png);
+
+ var job = await fx.ConvertAsync([source], new Preset
+ {
+ TargetFormat = "jpg",
+ Image = { RemoveBackground = true, Background = "#FF0000", Quality = 100 },
+ });
+
+ Assert.Equal(JobState.Completed, job.State);
+ using var result = new MagickImage(job.Outputs.Single());
+ var paper = Pixel(result, 5, 5);
+ Assert.True(paper.R > 240 && paper.G < 20 && paper.B < 20, paper.ToString());
+ }
+
+ [Fact]
+ public async Task Off_by_default_leaves_the_image_alone()
+ {
+ var dir = fx.NewFolder();
+ var source = Path.Combine(dir, "plain.png");
+ using (var image = Signature("white", "black"))
+ image.Write(source, MagickFormat.Png);
+
+ var job = await fx.ConvertAsync([source], new Preset { TargetFormat = "png" });
+
+ Assert.Equal(JobState.Completed, job.State);
+ using var result = new MagickImage(job.Outputs.Single());
+ Assert.Equal(255, Pixel(result, 5, 5).A);
+ Assert.Equal(255, Pixel(result, 5, 5).R);
+ }
+}