xxxxxxxxxx
118
/*************************************************
Slight change of https://editor.p5js.org/michaelshiloh/sketches/ZqXC5-6M0
DEMO
Capture Background while mouse is down, otherwise show subtraction
Keyboard press will show the background.
**************************************************/
let camera; // the camera object
let arraySize; // global to avoid recalculating
// every frame
let previous_frame = []; // the previous frame
let backgroundFrame = []; // Background Frame
let bac = 1; // number of how many average taken from background
function setup() {
createCanvas(400, 400);
pixelDensity(1);
camera = createCapture(VIDEO);
camera.size(400, 400);
// Number of pixels is the dimensions of the
// input device, and each pixel has 4
// components (red, green, blue, alpha)
arraySize = camera.width * camera.height * 4;
// Initialize the previous frame to blank
for (let i = 0; i < arraySize; i++) {
previous_frame.push = 0;
}
camera.hide();
}
function draw() {
background(0);
// Get the pixel array from the camera
camera.loadPixels();
if (keyIsPressed) {
showBackgroundFrame();
} else if (mouseIsPressed) {
print('Averaging Background...')
averageArray(backgroundFrame, camera.pixels);
} else {
// Get the pixel array from the canvas
loadPixels();
let curr_r, curr_g, curr_b;
let bg_r, bg_g, bg_b;
let diff_r, diff_g, diff_b; // computed differences
// For each pixel in the video frame
for (let i = 0; i < arraySize; i += 4) {
// Extract the red, green, and blue
// components from both the current
// and the previous pixel color
curr_r = camera.pixels[i + 0];
curr_g = camera.pixels[i + 1];
curr_b = camera.pixels[i + 2];
bg_r = backgroundFrame[i + 0];
bg_g = backgroundFrame[i + 1];
bg_b = backgroundFrame[i + 2];
// And calculate the differences
diff_r = abs(curr_r - bg_r);
diff_g = abs(curr_g - bg_g);
diff_b = abs(curr_b - bg_b);
// If the change is greater than threshold (50), display pixels
let t=80;
if ((diff_r + diff_g + diff_b > t)) {
pixels[i + 0] = curr_r;
pixels[i + 1] = curr_g;
pixels[i + 2] = curr_b;
} else {
pixels[i + 0] = 230;
pixels[i + 1] = 230;
pixels[i + 2] = 230;
}
}
// Write the pixels array to the canvas
updatePixels();
}
}
// Averages two arrays and put it in a1. If a1 is empty, a1=a2
function averageArray(a1, a2) {
if (a1.length == 0) {
for (let i = 0; i < a2.length; i++) {
append(a1,a2[i]);
}
} else {
for (let i = 0; i < a1.length; i++) {
a1[i] = round((a1[i]*bac + a2[i])/(bac+1));
}
bac++;
}
}
function showBackgroundFrame() {
loadPixels();
for (let i = 0; i < arraySize; i += 4) {
pixels[i + 0] = backgroundFrame[i + 0];
pixels[i + 1] = backgroundFrame[i + 1];
pixels[i + 2] = backgroundFrame[i + 2];
}
updatePixels();
}