import processing.video.*;
Capture video;
BlobDetector blobDetector;
color blobColor;
void setup() {
size(640, 480);
video = new Capture(this, width, height, 15);
video.start();
blobDetector = new BlobDetector();
blobColor = color(255, 0, 0);
smooth();
}
void draw() {
if (video.available()) {
video.read();
}
video.loadPixels();
// for black and white image
// video.filter(THRESHOLD,0.1);
image(video, 0, 0);
blobDetector.findBlob(blobColor, 20);
blobDetector.drawBlob();
blobDetector.drawBoundingBox();
blobDetector.drawCenterOfMass();
}
void mousePressed() {
int loc = mouseX + mouseY*video.width;
blobColor = video.pixels[loc];
}
class BlobDetector {
int blobPoints[][];
int blobWeight = 0;
PVector centerOfMass;
BlobDetector() {
blobPoints = new int[width][height];
centerOfMass = new PVector(0, 0);
}
void findBlob(color blobColor, int threshold) {
blobWeight = 0;
for (int x = 0; x < width; x ++ ) {
for (int y = 0; y < height; y ++ ) {
int loc = x + y*width;
color currentColor = video.pixels[loc];
PVector currColorVec = new PVector(red(currentColor), green(currentColor), blue(currentColor));
PVector trackColorVec = new PVector(red(blobColor), green(blobColor), blue(blobColor));
float diff = currColorVec.dist(trackColorVec);
if (diff < threshold) {
blobPoints[x][y] = 1;
blobWeight++;
} else {
blobPoints[x][y] = 0;
}
}
}
text(blobWeight, 20, 20);
}
void drawBlob() {
if (blobWeight > 200) {
for (int x = 0; x < width; x ++ ) {
for (int y = 0; y < height; y ++ ) {
if (blobPoints[x][y] == 1) {
strokeWeight(5);
stroke(255, 0, 0);
point(x, y);
}
}
}
}
}
void drawBoundingBox() {
PVector A = new PVector(width, height);
PVector B = new PVector(0, 0);
for (int x = 0; x < width; x ++ ) {
for (int y = 0; y < height; y ++ ) {
if (blobPoints[x][y] == 1) {
if (y < A.y)
A.y = y;
if (y > B.y)
B.y = y;
if (x < A.x)
A.x = x;
if (x > B.x)
B.x = x;
}
}
}
strokeWeight(1);
noFill();
rect(A.x, A.y, B.x-A.x, B.y-A.y);
text("A "+A.x+","+A.y, A.x, A.y);
text("B "+B.x+","+B.y, B.x, B.y);
}
void drawCenterOfMass() {
centerOfMass.set(0.0, 0.0, 0.0);
for (int x = 0; x < width; x ++ ) {
for (int y = 0; y < height; y ++ ) {
if (blobPoints[x][y] == 1) {
centerOfMass.x += x;
centerOfMass.y += y;
}
}
}
centerOfMass.x /= blobWeight;
centerOfMass.y /= blobWeight;
noStroke();
fill(255);
ellipse(centerOfMass.x, centerOfMass.y, 10, 10);
}
}
|