xxxxxxxxxx
90
let capture;
let previousPixels;
let thresholdAmount = 50;
let leftCounter = 0;
let rightCounter = 1;
function setup() {
createCanvas(640, 360);
capture = createCapture(VIDEO);
capture.size(640, 360);
capture.hide();
pixelDensity(1);
noStroke();
fill(0);
}
function copyImage(src, dst) {
let n = src.length;
if (!dst || dst.length != n) dst = new src.constructor(n);
while (n--) dst[n] = src[n];
return dst;
}
function draw() {
background(243);
frameDifference();
}
function frameDifference() {
capture.loadPixels();
let total = 0;
if (capture.pixels.length > 0) {
// don't forget this!
if (!previousPixels) {
previousPixels = copyImage(capture.pixels, previousPixels);
} else {
let t = thresholdAmount * 3; // 3 for r, g, b
for (let y = 0; y < capture.height; y++) {
for (let x = 0; x < capture.width; x++) {
let index = 4 * (width - 1 - x + y * width);
// calculate the differences
let rdiff = Math.abs(
capture.pixels[index + 0] - previousPixels[index + 0]
);
let gdiff = Math.abs(
capture.pixels[index + 1] - previousPixels[index + 1]
);
let bdiff = Math.abs(
capture.pixels[index + 2] - previousPixels[index + 2]
);
// copy the current pixels to previousPixels
previousPixels[index + 0] = capture.pixels[index + 0];
previousPixels[index + 1] = capture.pixels[index + 1];
previousPixels[index + 2] = capture.pixels[index + 2];
let diffs = rdiff + gdiff + bdiff;
let output = 0;
if (diffs > t) {
output = 255;
if (x < width / 2) {
leftCounter++;
} else {
rightCounter++;
}
}
capture.pixels[index] = output;
capture.pixels[index + 1] = output;
capture.pixels[index + 2] = output;
}
}
} // finished processing one frame
if (mouseIsPressed) capture.updatePixels();
push();
translate(width, 0);
scale(-1, 1);
image(capture, 0, 0, 640, 480);
pop();
print("left = " + leftCounter + " right = " + rightCounter);
if (leftCounter > 10 && rightCounter > 10) {
if (leftCounter > rightCounter) {
ellipse(width / 4, height / 2, 100);
} else {
ellipse((3 * width) / 4, height / 2, 100);
}
}
leftCounter = 0;
rightCounter = 0;
}
}