Skip to content

Instantly share code, notes, and snippets.

@Keyes
Created May 14, 2017 18:43
Show Gist options
  • Save Keyes/c033ba833a1fab870c1dc883710da2bf to your computer and use it in GitHub Desktop.
Save Keyes/c033ba833a1fab870c1dc883710da2bf to your computer and use it in GitHub Desktop.
let cv = require('opencv');
let fs = require('fs');
let Jimp = require('jimp');
const imageWidth = 640;
const imageHeight = 480;
const movementPadding = 10;
const pixelDiffThreshold = 50;
var diff = new cv.Matrix(imageWidth, imageHeight);
cv.readImage('last.jpg', function(err, image1) {
cv.readImage('prelast.jpg', function(err, image2) {
diff.absDiff(image1, image2);
diff.rectangle([imageWidth * 0.68, imageHeight * 0.52], [imageWidth * 0.29, imageHeight * 0.32], [0, 0, 0], -1); // TV
diff.rectangle([imageWidth * 0.05, imageHeight * 0.25], [imageWidth * 0.05, imageHeight * 0.15], [0, 0, 0], -1); // TV reflection
diff.rectangle([imageWidth * 0.15, imageHeight * 0.65], [imageWidth * 0.05, imageHeight * 0.11], [0, 0, 0], -1); // TV reflection
diff.convertGrayscale();
var changedPixels = 0;
var motionBox = { x: [imageWidth, 0], y: [imageHeight, 0] };
Jimp.read(diff.toBuffer(), function (err, image) {
image.scan(0, 0, imageWidth, imageHeight, function (x, y, idx) {
var brightness = 0.34 * this.bitmap.data[ idx + 0 ] + 0.5 * this.bitmap.data[ idx + 1 ] + 0.16 * this.bitmap.data[ idx + 2 ]; // get RGB values to calculate brightness
if (brightness >= pixelDiffThreshold) {
changedPixels++;
this.bitmap.data[ idx + 0 ] = brightness;
this.bitmap.data[ idx + 1 ] = brightness;
this.bitmap.data[ idx + 2 ] = brightness;
// calculate area of movement
if (x < motionBox.x[0]) motionBox.x[0] = x;
if (y < motionBox.y[0]) motionBox.y[0] = y;
if (x > motionBox.x[1]) motionBox.x[1] = x;
if (y > motionBox.y[1]) motionBox.y[1] = y;
} else {
this.bitmap.data[ idx + 0 ] = 0;
this.bitmap.data[ idx + 1 ] = 0;
this.bitmap.data[ idx + 2 ] = 0;
}
});
image.write( 'diff.jpg', saved); // save the diff graphic
image1.rectangle(
[
(motionBox.x[0] - movementPadding),
(motionBox.y[0] - movementPadding)
], [
(motionBox.x[1] - motionBox.x[0] + (movementPadding * 2)),
(motionBox.y[1] - motionBox.y[0] + (movementPadding * 2))
],
[0, 255, 0],
1
);
image1.save('movement.jpg', saved); // use image1 to show the changed area
});
});
});
function saved() {
console.log('image saved!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment