xxxxxxxxxx
108
/*************************************************
Frame differencing with color
Based on Code listing 1 from
Golan Levin's Computer vision for artists and
designers, as implemented in
https://github.com/michaelshiloh/resourcesForClasses/blob/master/src/processingSketches/computerVision/frameDifferencing/frameDifferencing.pde
Change log:
01 mar 2022 - ms - Modified Processing sketch
to work with p5.js
02 mar 2022 - ms - revised based on class
feedback
Each pixel in the current frame is compared
to the corresponding pixel in the saved
previous frame, and any difference is
written to the canvas. Thus the canvas only
displays the differences between the current
frame and the previous frame.
**************************************************/
// 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) {
// 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();
}