Search code examples
image-processingcolorsimage-manipulation

Given a background and foreground color, how to calculate the mix amount between them in an image?


I have an input image looking like this:

input image

As you can see, it's a restore window icon with a blue tint and a background in a pink color.

There are some pixels which are a mix of both colors by an amount I want to calculate, but don't know how. The 100% background and 100% foreground color is given.

Eventually, I want to create an alpha bitmap in which the RGB amounts of every pixel is the foreground color RGB, but the alpha channel is the mix amount:

output image


Solution

  • I found the answer (myself) after discussing with some mathematicians over at math.stackexchange.

    Please read my answer there for the logic behind this; in C#, the code would be like this:

    private static double GetMixAmount(Color fore, Color back, Color input)
    {
        double lengthForeToBack = GetLengthBetween3DVectors(fore, back);
        double lengthForeToInput = GetLengthBetween3DVectors(fore, input);
        return 1 / (lengthForeToBack / lengthForeToInput);
    }
    
    private static double GetLengthBetween3DVectors(Color a, Color b)
    {
        // Typical length between two 3-dimensional points - simply handle RGB as XYZ!
        return Math.Sqrt(
            Math.Pow(a.R - b.R, 2) + Math.Pow(a.G - b.G, 2) + Math.Pow(a.B - b.B, 2));
    }
    

    If you don't know if the foreground and background colors can really be mixed to result in the input color, make sure to clamp the alpha value to lie between 0.0 and 1.0.