Remove a gradient background from a product photo

View as Markdown

Background RemovalPipelineTransform

This sample shows how to cut a product out of a studio shot whose background is not a flat colour but a soft gradient, using the ContiguousBackgroundRemoval transform in a pipeline. Tolerance limits how far a background pixel may be from the background colour, while StepTolerance lets the background change gradually from pixel to pixel and stops at the sharp edge of the product. Colour differences are measured in CIE L*a*b* (delta E), so the values follow what the eye sees. The pipeline keeps memory use bounded, so the same code works for very large images.

Code Snippet

using (var reader = ImageReader.Create("Apple.jpg"))
using (var removal = new ContiguousBackgroundRemoval())
using (var writer = new PngWriter("RemoveContiguousBackgroundMemoryFriendly.png"))
{
    // The backdrop gets darker towards the bottom: allow a larger total difference from the
    // background colour, but only small steps between neighbouring pixels.
    removal.Tolerance = 30;
    removal.StepTolerance = 4;

    Pipeline.Run(reader + removal + writer);
}

Input

Apple.jpg

Apple.jpg

Output

RemoveContiguousBackgroundMemoryFriendly.png

RemoveContiguousBackgroundMemoryFriendly.png

Used APIs