Mick
Mick

Reputation: 7947

Quick way to estimate difference between colours

I am implementing an image processing task in which I am comparing colours of pixels a huge number of times and I need the comparison code to execute as fast as possible. Currently the image is in ARGB_8888 format: I am ignoring transparency. So I am using the sum of absolute differences in red, green and blue as my measure of the difference in colour, though this choice of difference measure is not set in stone (e.g. maybe the sum of the squares of the differences may be better in some sense).

int coldif(int c1,int c2)
{
    return (Math.abs(( c1&0xff)          -( c2&0xff)))             +
           (Math.abs(((c1&0xff00)>> 8)   -((c2&0xff00)>> 8)) )     +
           (Math.abs(((c1&0xff0000)>> 16)-((c2&0xff0000)>> 16)));
}

So I am interested in ways of making my existing algorithm faster, or alternatively using a different measure of colour difference, or even converting the entire image into a different colour representation as a pre-process which would then allow a different colour difference algorithm to be used.

Upvotes: 1

Views: 88

Answers (2)

Oleg Estekhin
Oleg Estekhin

Reputation: 8415

Another variant that is a bit faster but still can be useful to compare differences between multiple color pairs:

int coldif( int c1, int c2 ) {
    int d = c1 ^ c2;
    return ( d & 0xff ) + ( ( d >>> 8 ) & 0xff ) + ( ( d >>> 16 ) & 0xff );
}

Upvotes: 0

Axel
Axel

Reputation: 14169

Is this really a bottleneck? What I can think of is reducing the amount of shift operations like this:

int coldif(int c1,int c2)
{
    return (Math.abs((c1&0x0000ff) - (c2&0x0000ff))      ) +
           (Math.abs((c1&0x00ff00) - (c2&0x00ff00)) >>  8) +
           (Math.abs((c1&0xff0000) - (c2&0xff0000)) >> 16);
}

Upvotes: 2

Related Questions