Motion Detection
About this demonstration
This is an example of using a webcam to detect a user's motion on a region at the top of the screen.
It uses the following approach:
- we blend the current frame with the previous frame to calculate what changed in between - this is based on the work by Romuald Quantin.
- we take the top fifth of the video stream, split it into eight regions and if on average more than 10% of pixels have changed we can trigger some action for that region.
View the motionPlayer.js source on Github to see how the code works.
Usage example
<div id="videoContainer">
<video id="inputVideo" autoplay></video>
<canvas id="overlay"></canvas>
</div>
<script data-main="javascripts/eyePlayer.min.js" src="javascripts/require.js"></script>
<script type="text/javascript">
require(['motionPlayer'], function(motionPlayer) {
var scale = 1/3;
var video = document.getElementById('inputVideo');
var canvas = document.getElementById('overlay');
var motionplayer = new motionPlayer({
scale: scale, // scale the webcam image down to improve performance
filter: function(image) { // add a filter to the processed image, e.g. make it semi transparent
data = image.data;
for (var i=0; i<data.length; i+=4) {
data[i+3] = 50;
}
}
});
var ctx = canvas.getContext('2d');
motionplayer.init(video, canvas);
motionplayer.start();
document.addEventListener('motionEvent', function(event) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
// draw the motion image
ctx.drawImage(event.image, 0, canvas.height-(canvas.height*scale), canvas.width*scale, canvas.height*scale);
for (var i=0; i<event.regions.length; i++) {
if (event.regions[i] > 0) {
// SOMETHING HAPPENED IN THIS REGION
}
}
});
});
</script>
View source of this page to see a more complete example.