xxxxxxxxxx
148
let video;
let trackColor;
let threshold = 25;
let distThreshold = 50;
let blobs = [];
function setup() {
createCanvas(640, 360);
let cameras = [];
video = createCapture(VIDEO);
video.size(640, 360);
video.hide();
trackColor = color(255, 0, 0);
}
function keyPressed() {
if (key === 'a') {
distThreshold += 5;
} else if (key === 'z') {
distThreshold -= 5;
}
if (key === 's') {
threshold += 5;
} else if (key === 'x') {
threshold -= 5;
}
console.log(distThreshold);
}
function draw() {
video.loadPixels();
image(video, 0, 0);
blobs = [];
// Begin loop to walk through every pixel
for (let x = 0; x < video.width; x++) {
for (let y = 0; y < video.height; y++) {
let loc = x + y * video.width;
// What is current color
let currentColor = video.pixels[loc];
let r1 = red(currentColor);
let g1 = green(currentColor);
let b1 = blue(currentColor);
let r2 = red(trackColor);
let g2 = green(trackColor);
let b2 = blue(trackColor);
let d = distSq(r1, g1, b1, r2, g2, b2);
if (d < threshold * threshold) {
let found = false;
for (let i = 0; i < blobs.length; i++) {
if (blobs[i].isNear(x, y)) {
blobs[i].add(x, y);
found = true;
break;
}
}
if (!found) {
let b = new Blob(x, y);
blobs.push(b);
}
}
}
}
for (let i = 0; i < blobs.length; i++) {
if (blobs[i].size() > 500) {
blobs[i].show();
}
}
textAlign(RIGHT);
fill(0);
text("distance threshold: " + distThreshold, width - 10, 25);
text("color threshold: " + threshold, width - 10, 50);
}
function distSq(x1, y1, x2, y2) {
let d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
return d;
}
function distSq(x1, y1, z1, x2, y2, z2) {
let d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1);
return d;
}
function mousePressed() {
let loc = mouseX + mouseY * video.width;
trackColor = video.pixels[loc];
}
class Blob {
constructor(x, y) {
this.minx = x;
this.miny = y;
this.maxx = x;
this.maxy = y;
this.points = [];
this.points.push(createVector(x, y));
}
show() {
stroke(0);
fill(255);
strokeWeight(2);
rectMode(CORNERS);
rect(this.minx, this.miny, this.maxx, this.maxy);
// for (let i = 0; i < this.points.length; i++) {
// stroke(0, 0, 255);
// point(this.points[i].x, this.points[i].y);
// }
}
add(x, y) {
this.points.push(createVector(x, y));
this.minx = min(this.minx, x);
this.miny = min(this.miny, y);
this.maxx = max(this.maxx, x);
this.maxy = max(this.maxy, y);
}
size() {
return (this.maxx - this.minx) * (this.maxy - this.miny);
}
isNear(x, y) {
let d = 10000000;
for (let i = 0; i < this.points.length; i++) {
let tempD = distSq(x, y, this.points[i].x, this.points[i].y);
if (tempD < d) {
d = tempD;
}
}
if (d < distThreshold * distThreshold) {
return true;
} else {
return false;
}
}
}