Loading...
Logo
Processing Forum
I need to be able to find the pixel whose color is closest to some color c.  I am doing this thousands of times and need a way to do it *fast*.  The loop-based way I wrote below is taking too long (by a factor of at least 100x!).  Is there a much more efficient way to locate the individual pixel whose distance from c is at a minimum?

Bad code follows...

int mindist = 1000;
int currdist, r1, g1, b1;
int bestX = width/2; int bestY = height/2;
color c1 = color(255,255,255);

for (int i = 0; i<width; i++) {
  for (int j = 0; j<height; j++) {
    c1 = get(i,j);
    r1 = (int)red(c1); g1 = (int)green(c1); b1 = (int)blue(c1);
    currdist = abs(r-r1) + abs(g-g1) + abs(b-b1) + abs(g-g1);
    if (currdist<mindist) {
      bestX = i;
      bestY = y;
    }
  }

Replies(2)

(it's also wrong - uses y at the end rather than j. also the distance thing is probably better done using pythagorus, although that'll be even slower)

http://processing.org/reference/get_.html says:

"Getting the color of a single pixel with get(x, y) is easy, but not as fast as grabbing the data directly from pixels[]. The equivalent statement to "get(x, y)" using pixels[] is "pixels[y*width+x]". Processing requires calling loadPixels() to load the display window data into the pixels[] array before getting the values. "

but it might be better to pre-sort all the values of pixels so you don't need to linear search through height x width of them every time.


I suggest to use the toxiclibs colorutils package. There is an example providing you exaclty this functionality that is much more complex than It seems.

After installing the complete set of packages you will find an example called ImageColors. This example contains a very efficient way to compare "color distances".



Download the example and try to hack it. I think this should drive you direct to a closest color function ;-)

More info in this thread of the Processing Forum about "range of color" (where toxi suggests to use colorutils...) :-)

Anyway remember that to calculate color distances you should use HSV and not RGB color mode!!!

Hope this help,
dw