Hardware Reference
In-Depth Information
The draw() method begins by
establishing a value for the closest
matching color, a threshold for similar-
ity, and X and Y positions of the closest
matching pixel. Then it reads the
camera and saves the resulting image
in a pixel array.
8
void draw() {
float closestMatch = 500; // value representing the closest color match
float colorThreshold = 10; // the threshold of color similarity
int closestX = 0; // horizontal position of the closest color
int closestY = 0; // vertical position of the closest color
// read the camera:
opencv.read();
// draw the camera image to the window:
image(opencv.image(), 0, 0);
// copy the camera pixel array:
pixelArray = opencv.pixels();
Next comes a pair of nested for
loops that iterates over the rows and
columns of pixels. This is a standard
algorithm for examining all the pixels
of an image. With each pixel, you
determine its position in the array with
the following formula (which you'll see
frequently.)
8
// Begin loop to walk through every pixel
for (int x = 0; x < opencv.width; x++ ) {
for (int y = 0; y < opencv.height; y++ ) {
// calculate the pixel's position in the array
// based on its width and height:
int loc = x + y*opencv.width;
// get the color of the current pixel:
color currentColor = pixelArray[loc];
float r1 = red(currentColor);
float g1 = green(currentColor);
float b1 = blue(currentColor);
float r2 = red(trackColor);
float g2 = green(trackColor);
float b2 = blue(trackColor);
arrayLocation = x + (y * width);
Once you have the pixel's position, you
extract the red, green, and blue values,
as well as the values for the color you
wish to track.
8
Next, calculate the difference between
the two colors. By treating the red, green,
and blue values of each color as positions
in 3-dimensional space, you can find the
difference by calculating the Euclidean
distance between them. Processing's dist()
function is handy for this.
// use the dist() function to figure the aggregate color
// of the current pixel. This method treats the red, green, and blue
// of the current pixel's color and of the target color as
// coordinates
// in 3D space and calculates the difference between them
// as Euclidean distance.
// In this formula, closer distance = closer color similarity:
float d = dist(r1, g1, b1, r2, g2, b2);
Once you know the difference, compare
that to the closest match so far (which was
set arbitrarily high for the first match). If the
current difference is less than the closest
match, the current pixel is the new closest
match.
// If current color is more similar to tracked color than
// closest color, save current location and current difference
if (d < closestMatch) {
closestMatch = d;
closestX = x;
closestY = y;
}
}
}
ยป
 
Search WWH ::




Custom Search