Identify closest pixel in color efficiently
in
Programming Questions
•
2 years ago
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;
}
}
1