Question

I have 2 bytes representing color in an 8-bit format

MSB  LSB
01234567
  RRGGBB

Bits 0 and 1 are trash.

To blend two colors, should I just average the bits per color?

R1 = ( C1 ^ 00110000B ) >> 4;
G1 = ( C1 ^ 00001100B ) >> 2;
B1 = ( C1 ^ 00000011B );

R2 = ( C2 ^ 00110000B ) >> 4;
G2 = ( C2 ^ 00001100B ) >> 2;
B2 = ( C2 ^ 00000011B );

R3 = avg( R1 , R2 ) << 4;
G3 = avg( G1 , G2 ) << 2;
B3 = avg( B1 , B2 );

C3 = R3 + G3 + B3

Where C1 is the 1st color, C2 is the second, C3 is the blended color, ^ is bitwise AND, >> is bitwise shift right, << is bitwise shift left, xxxxxxxxB is a binary number and avg( a , b ) is the arithmetic mean.

Was it helpful?

Solution

You can think of colours are points in a 3D space. The definition of "average" depends on what space you use. You will get different results if you average RGB, HSL, or something more "exotic".

But if you're limited to 2 bits per colour then none of that is really going to matter much and what you suggest is fine (except, as noted in the comments, you need &, and not ^, to mask).

(By "average" I assume you mean add the bits (per colour) and divide by 2 (right shift). Note that if you do this repeatedly (eg avg two images, then avg the result with a third, then avg the result of that with a fourth) then you'll eventually end up with something black because the right shift rounds down, so you're slightly biased to lower values).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top