Click here to Skip to main content
15,891,976 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Trying to detect source color after mixing it with another one.

What I have tried:

For example:
			A	R	G	B
source		255	128	64	64
overlay		204	0	128	128
result		255	26	115	115
After mixing source color with overlay (with normal blending mode), i get the result color.
Knowing, that source alpha and result alpha are constants, for calculating result color I use this formula:
result.red = source.red + (overlay.red - source.red) * overlay.alpha / 255;
respectively for the rest blue and green channels the same formula.
The first trouble I face, is that the result value is rounded, so instead of 25.6 (for result R), I will get 26 (because rgb are byte values).
So, this will cause the problem while detecting source color, knowing only result and overlay. So, using this formula:
source.red = (255 * result.red - overlay.red * overlay.alpha) / (255 - overlay.alpha)
will result source red value = 130 insted of 128 (because result red value is 26 insted of 25.6).
Any ideas how the source color can be calculated another way?
Posted
Updated 7-Oct-17 14:54pm

The only way to avoid problems introduced due to rounding is to avoid rounding.

In your description you did not mention what the data types for the colors are, but it seems they are integers, so every precision of your calculation that is "rounded away" is gone in the integer case and there is no way to get this back.

One option to prevent this situation is to store your colors as either floating point or fixed point values so you are not loosing precision due to rounding. If this is possible depends on other constraints of your problem.

Another option that would be possible is instead of trying to calculate the source value, to calculate a source range. In your example of a result color of 26 you would solve the source color for a result color of 25.5 and 26.5. That will lead to a minimal and maximal source color that yields the rounded result color. This might not provide you with your original source color (which is an impossible task), but you know, in which range the source was.
 
Share this answer
 
Quote:
The first trouble I face, is that the result value is rounded, so instead of 25.6 (for result R), I will get 26 (because rgb are byte values).

That is the problem when you use integers in a formula that use division and that what is divided is not multiple of divisor. There is unavoidable lost.
Quote:
Any ideas how the source color can be calculated another way?

There is no solution as long as long as you stick with integers and you can can't change it since colors are integers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900