xxxxxxxxxx
82
/*************************************************
Slight change of https://editor.p5js.org/michaelshiloh/sketches/ZqXC5-6M0
**************************************************/
let camera0; // the camera0 object
let arraySize; // global to avoid recalculating
// every frame
let previous_frame = []; // the previous frame
let threshold = 100;
function setup() {
createCanvas(400, 400);
pixelDensity(1);
camera0 = createCapture(VIDEO);
camera0.size(400, 400);
// Number of pixels is the dimensions of the
// input device, and each pixel has 4
// components (red, green, blue, alpha)
arraySize = camera0.width * camera0.height * 4;
// Initialize the previous frame to blank
for (let i = 0; i < arraySize; i++) {
previous_frame.push = 0;
}
camera0.hide();
}
function draw() {
background(0)
// Get the pixel array from the camera0
camera0.loadPixels();
// Get the pixel array from the canvas
loadPixels();
let curr_r, curr_g, curr_b;
let prev_r, prev_g, prev_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 = camera0.pixels[i + 0];
curr_g = camera0.pixels[i + 1];
curr_b = camera0.pixels[i + 2];
prev_r = previous_frame[i + 0];
prev_g = previous_frame[i + 1];
prev_b = previous_frame[i + 2];
// And calculate the differences
diff_r = abs(curr_r - prev_r);
diff_g = abs(curr_g - prev_g);
diff_b = abs(curr_b - prev_b);
// If difference is greater than threshold, set the pixel white
let pixelColor = ((diff_r+diff_g+diff_b)>threshold) ? 255:0;
pixels[i + 0] = pixelColor;
pixels[i + 1] = pixelColor;
pixels[i + 2] = pixelColor;
// The current pixel becomes
// the previous pixel for the next frame
previous_frame[i + 0] = curr_r;
previous_frame[i + 1] = curr_g;
previous_frame[i + 2] = curr_b;
}
// Write the pixels array to the canvas
updatePixels();
}