Search code examples
image-processingcomputer-visioninterpolationlinear-interpolationbilinear-interpolation

How to find the fractional weighting of n colors which contribute to a known color C?


This is related to but not the same as this question (click to go to). However the linked question would need to be solved before this one, or at least the problem understood. This could be considered to be the reverse of the other.

This problem is, given n colors in RGB such as

Color1 as RGB (255, 128, 128)
Color2 as RGB (128, 128, 128)
Color3 as RGB (128, 0, 128)

We know a given color C, find the fractional weighting of each color so that when these colors are mixed given that fractional weighting the resultant color given results in the known color C. Fractional weighting is defined in the linked question above, it is a value between 0.0 and 1.0 where the total weights equals 1.0. For Example Color1 could be 0.2, Color2 be 0.2 and Color3 be 0.6.

Interpolation is linear in RGB color space.

Usually the number of colors wouldn't exceed 5, it would normally be 2 or 3 or 4 colors.

Note that it is quite possible that there is no way to mix these colors to obtain color C, for example if we have two very red colors and I want color C (which is green), there's no way to mix two red's to get green. So in that case, there is no solution.

Also under some conditions there may be multiple ways to mix the colors to make color C.


Solution

  • Yes so linear equations helps to solve the problem. Some Java code which solves the problem is located here, note that it builds with Scala SBT but its Java code.

    https://github.com/PhilAndrew/betweenrgb

    The merging of weighted colors is tested here:

    https://github.com/PhilAndrew/betweenrgb/blob/master/src/test/java/between/rgb/FindWeightedColorsTest.java