How to remove background from an image
How to remove background from an image
In the example below, to carefully remove background, we use the class AutoMaskingGraphCutOptions class with automatically calculated strokes and set FeatheringRadius property to smooth and blur the cutting edge. The feathering radius is calculated as 1/500 of the image dimension. After removing a background we need to set the color to replace it, so we use transparent pixels in this case. The same procedure we can use for photo background change.
using Aspose.Imaging; | |
using Aspose.Imaging.FileFormats.Png; | |
using Aspose.Imaging.ImageOptions; | |
using Aspose.Imaging.Masking; | |
using Aspose.Imaging.Masking.Options; | |
using Aspose.Imaging.Masking.Result; | |
using Aspose.Imaging.Sources; | |
using System; | |
using System.IO; | |
string templatesFolder = @"c:\Users\USER\Downloads\templates\"; | |
string dataDir = templatesFolder; | |
MaskingResult results; | |
using (RasterImage image = (RasterImage)Image.Load(dataDir + "couple.jpg")) | |
{ | |
// To use Graph Cut with auto calculated strokes, AutoMaskingGraphCutOptions is used. | |
AutoMaskingGraphCutOptions options = new AutoMaskingGraphCutOptions | |
{ | |
// Indicating that a new calculation of the default strokes should be performed during the image decomposition. | |
CalculateDefaultStrokes = true, | |
// Setting post-process feathering radius based on the image size. | |
FeatheringRadius = (Math.Max(image.Width, image.Height) / 500) + 1, | |
Method = SegmentationMethod.GraphCut, | |
Decompose = false, | |
ExportOptions = | |
new PngOptions() | |
{ | |
ColorType = PngColorType.TruecolorWithAlpha, | |
Source = new FileCreateSource(dataDir + "result.png") | |
}, | |
BackgroundReplacementColor = Color.Transparent | |
}; | |
results = new ImageMasking(image).Decompose(options); | |
using (RasterImage resultImage = (RasterImage)results[1].GetImage()) | |
{ | |
resultImage.Save(dataDir + "result2.png", new PngOptions() { ColorType = PngColorType.TruecolorWithAlpha }); | |
} | |
} | |
File.Delete(dataDir + "result.png"); | |
File.Delete(dataDir + "result2.png"); |
For a more detailed description with examples of how to remove background please follow the Aspose removing background documentation.