xxxxxxxxxx
103
/*************************************************
mirror with some other features experiment
**************************************************/
// Always declare variables. Although Javascript
// is very tolerant, it's not a good idea to
// depend on it.
let camera; // the camera object
let arraySize; // global to avoid recalculating
// every frame
let previous_frame = []; // the previous frame
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();
// 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) {
for (let y = 0; y < camera.height; y++) {
for (let x = 0; x < camera.width; x++) {
// let index = 4 * (x + y * width);
// flip the x to make software mirror
let i = 4 * (width - 1 - x + y * width);
print ("x = " + x + " y = " + y + " i = " + i)
// 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];
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);
// Put the difference pixel in the pixels array
pixels[i + 0] = diff_r;
pixels[i + 1] = diff_g;
pixels[i + 2] = diff_b;
let diffs = diff_r + diff_g + diff_b;
if (diffs > 200) {
pixels[i + 0] = 255;
pixels[i + 1] = 255;
pixels[i + 2] = 255;
} else {
pixels[i + 0] = 0;
pixels[i + 1] = 0;
pixels[i + 2] = 0;
}
// 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();
}