SHARE
TWEET

JS Webcam Motion Detection Night Vision SRC V13 Coded By BrU

a guest Jan 25th, 2020 116 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. <!--
  3. Created using JS Bin
  4. http://jsbin.com
  5.  
  6. Copyright (c) 2020 by anonymous (http://jsbin.com/bajamohibi/1/edit)
  7.  
  8. Released under the MIT license: http://jsbin.mit-license.org
  9. -->
  10. <meta name="robots" content="noindex">
  11. <meta name="robots" content="noindex">
  12. <body>
  13. <font color="white">
  14.       <center>
  15.         <figure>
  16.             <video id="video" hidden></video>
  17.         </figure>
  18.  
  19.         <figure>
  20.             <canvas id="motion"></canvas>
  21.             <figcaption>        
  22.  
  23.             <br>
  24.                  <span id="score"></span><p>
  25.                  <button id="reset" onclick="script:ammount=0;majamm=0;large=0;vlarge=0;extreme=0;max=0;max1=0;">Reset All</button>
  26.                   <button id="stats" onclick="script:if(majamm!=0){majamm--;}
  27.                                               alert('Minor Movement: '+ammount);alert('Major Movement: '+majamm);alert('Large Movement: '+large);alert('Very Large Movement: '+vlarge);alert('Extreme Movement: '+extreme);alert('Extremely Large Movement: '+max);alert('Maximum Movement: '+max1);">View Movement Statistics</button>
  28.                  
  29.             </figcaption>
  30.         </figure><p>
  31.        
  32.    
  33. <script>
  34. var DiffCamEngine = (function() {
  35.     var stream;                 // stream obtained from webcam
  36.     var video;                  // shows stream
  37.     var captureCanvas;          // internal canvas for capturing full images from video
  38.     var captureContext;         // context for capture canvas
  39.     var diffCanvas;             // internal canvas for diffing downscaled captures
  40.     var diffContext;            // context for diff canvas
  41.     var motionCanvas;           // receives processed diff images
  42.     var motionContext;          // context for motion canvas
  43.  
  44.     var initSuccessCallback;    // called when init succeeds
  45.     var initErrorCallback;      // called when init fails
  46.     var startCompleteCallback;  // called when start is complete
  47.     var captureCallback;        // called when an image has been captured and diffed
  48.  
  49.     var captureInterval;        // interval for continuous captures
  50.     var captureIntervalTime;    // time between captures, in ms
  51.     var captureWidth;           // full captured image width
  52.     var captureHeight;          // full captured image height
  53.     var diffWidth;              // downscaled width for diff/motion
  54.     var diffHeight;             // downscaled height for diff/motion
  55.     var isReadyToDiff;          // has a previous capture been made to diff against?
  56.     var pixelDiffThreshold;     // min for a pixel to be considered significant
  57.     var scoreThreshold;         // min for an image to be considered significant
  58.     var includeMotionBox;       // flag to calculate and draw motion bounding box
  59.     var includeMotionPixels;    // flag to create object denoting pixels with motion
  60.  
  61.     function init(options) {
  62.    
  63.         // sanity check
  64.         if (!options) {
  65.             throw 'No options object provided';
  66.         }
  67.  
  68.         // incoming options with defaults
  69.         video = options.video || document.createElement('video');
  70.         motionCanvas = options.motionCanvas || document.createElement('canvas');
  71.         captureIntervalTime = options.captureIntervalTime || 100;
  72.         captureWidth = options.captureWidth || 850;
  73.         captureHeight = options.captureHeight || 450;
  74.         diffWidth = options.diffWidth || 850;
  75.         diffHeight = options.diffHeight || 450;
  76.         pixelDiffThreshold = options.pixelDiffThreshold || 32;
  77.         scoreThreshold = options.scoreThreshold || 16;
  78.         includeMotionBox = options.includeMotionBox || false;
  79.         includeMotionPixels = options.includeMotionPixels || false;
  80.  
  81.         // callbacks
  82.         initSuccessCallback = options.initSuccessCallback || function() {};
  83.         initErrorCallback = options.initErrorCallback || function() {};
  84.         startCompleteCallback = options.startCompleteCallback || function() {};
  85.         captureCallback = options.captureCallback || function() {};
  86.  
  87.         // non-configurable
  88.         captureCanvas = document.createElement('canvas');
  89.         diffCanvas = document.createElement('canvas');
  90.       var img=document.getElementById('img')
  91.         isReadyToDiff = false;
  92.  
  93.         // prep video
  94.         video.autoplay = true;
  95.  
  96.         // prep capture canvas
  97.         captureCanvas.width = captureWidth;
  98.         captureCanvas.height = captureHeight;
  99.         captureContext = captureCanvas.getContext('2d');
  100.  
  101.         // prep diff canvas
  102.         diffCanvas.width = diffWidth;
  103.         diffCanvas.height = diffHeight;
  104.         diffContext = diffCanvas.getContext('2d');
  105.  
  106.         // prep motion canvas
  107.         motionCanvas.width = diffWidth;
  108.         motionCanvas.height = diffHeight;
  109.         motionContext = motionCanvas.getContext('2d');
  110.  
  111.         requestWebcam();
  112.     }
  113.  
  114.     function requestWebcam() {
  115.         var constraints = {
  116.             audio: false,
  117.             video: { width: captureWidth, height: captureHeight }
  118.         };
  119.  
  120.         navigator.mediaDevices.getUserMedia(constraints)
  121.             .then(initSuccess)
  122.             .catch(initError);
  123.     }
  124.  
  125.     function initSuccess(requestedStream) {
  126.         stream = requestedStream;
  127.         initSuccessCallback();
  128.     }
  129.  
  130.     function initError(error) {
  131.         console.log(error);
  132.         initErrorCallback();
  133.     }
  134.  
  135.     function start() {
  136.         if (!stream) {
  137.             throw 'Cannot start after init fail';
  138.         }
  139.  
  140.         // streaming takes a moment to start
  141.         video.addEventListener('canplay', startComplete);
  142.         video.srcObject = stream;
  143.     }
  144.  
  145.     function startComplete() {
  146.         video.removeEventListener('canplay', startComplete);
  147.         captureInterval = setInterval(capture, captureIntervalTime);
  148.         startCompleteCallback();
  149.     }
  150.  
  151.     function stop() {
  152.         clearInterval(captureInterval);
  153.         video.src = '';
  154.         motionContext.clearRect(0, 0, diffWidth, diffHeight);
  155.         isReadyToDiff = false;
  156.     }
  157.  
  158.     function capture() {
  159.         // save a full-sized copy of capture
  160.         captureContext.drawImage(video, 0, 0, captureWidth, captureHeight);
  161.         var captureImageData = captureContext.getImageData(0, 0, captureWidth, captureHeight);
  162.  
  163.         // diff current capture over previous capture, leftover from last time
  164.         diffContext.globalCompositeOperation = 'difference';
  165.         diffContext.drawImage(video, 0, 0, diffWidth, diffHeight);
  166.         var diffImageData = diffContext.getImageData(0, 0, diffWidth, diffHeight);
  167.  
  168.         if (isReadyToDiff) {
  169.             var diff = processDiff(diffImageData);
  170.  
  171.             motionContext.putImageData(diffImageData, 0, 0);
  172.             if (diff.motionBox) {
  173.                 motionContext.strokeStyle = '#fff';
  174.                 motionContext.strokeRect(
  175.                     diff.motionBox.x.min + 0.5,
  176.                     diff.motionBox.y.min + 0.5,
  177.                     diff.motionBox.x.max - diff.motionBox.x.min,
  178.                     diff.motionBox.y.max - diff.motionBox.y.min
  179.                 );
  180.             }
  181.             captureCallback({
  182.                 imageData: captureImageData,
  183.                 score: diff.score,
  184.                 hasMotion: diff.score >= scoreThreshold,
  185.                 motionBox: diff.motionBox,
  186.                 motionPixels: diff.motionPixels,
  187.                 getURL: function() {
  188.                     return getCaptureUrl(this.imageData);
  189.                 },
  190.                 checkMotionPixel: function(x, y) {
  191.                     return checkMotionPixel(this.motionPixels, x, y)
  192.                 }
  193.             });
  194.         }
  195.  
  196.         // draw current capture normally over diff, ready for next time
  197.         diffContext.globalCompositeOperation = 'source-over';
  198.         diffContext.drawImage(video, 0, 0, diffWidth, diffHeight);
  199.         isReadyToDiff = true;
  200.     }
  201.  
  202.     function processDiff(diffImageData) {
  203.         var rgba = diffImageData.data;
  204.  
  205.         // pixel adjustments are done by reference directly on diffImageData
  206.         var score = 0;
  207.         var motionPixels = includeMotionPixels ? [] : undefined;
  208.         var motionBox = undefined;
  209.         for (var i = 0; i < rgba.length; i += 4) {
  210.             var pixelDiff = rgba[i] * 0.3 + rgba[i + 1] * 0.6 + rgba[i + 2] * 0.1;
  211.             var normalized = Math.min(255, pixelDiff * (255 / pixelDiffThreshold));
  212.             rgba[i] = normalized;
  213.             rgba[i + 1] = normalized^255;
  214.             rgba[i + 2] = 0;
  215.  
  216.             if (pixelDiff >= pixelDiffThreshold) {
  217.                 score++;
  218.                 coords = calculateCoordinates(i / 4);
  219.  
  220.                 if (includeMotionBox) {
  221.                     motionBox = calculateMotionBox(motionBox, coords.x, coords.y);
  222.                 }
  223.  
  224.                 if (includeMotionPixels) {
  225.                     motionPixels = calculateMotionPixels(motionPixels, coords.x, coords.y, pixelDiff);
  226.                 }
  227.  
  228.             }
  229.         }
  230.  
  231.         return {
  232.             score: score,
  233.             motionBox: score > scoreThreshold ? motionBox : undefined,
  234.             motionPixels: motionPixels
  235.         };
  236.     }
  237.  
  238.     function calculateCoordinates(pixelIndex) {
  239.         return {
  240.             x: pixelIndex % diffWidth,
  241.             y: Math.floor(pixelIndex / diffWidth)
  242.         };
  243.     }
  244.  
  245.     function calculateMotionBox(currentMotionBox, x, y) {
  246.         // init motion box on demand
  247.         var motionBox = currentMotionBox || {
  248.             x: { min: coords.x, max: x },
  249.             y: { min: coords.y, max: y }
  250.         };
  251.  
  252.         motionBox.x.min = Math.min(motionBox.x.min, x);
  253.         motionBox.x.max = Math.max(motionBox.x.max, x);
  254.         motionBox.y.min = Math.min(motionBox.y.min, y);
  255.         motionBox.y.max = Math.max(motionBox.y.max, y);
  256.  
  257.         return motionBox;
  258.     }
  259.  
  260.     function calculateMotionPixels(motionPixels, x, y, pixelDiff) {
  261.         motionPixels[x] = motionPixels[x] || [];
  262.         motionPixels[x][y] = true;
  263.  
  264.         return motionPixels;
  265.     }
  266.  
  267.     function getCaptureUrl(captureImageData) {
  268.         // may as well borrow captureCanvas
  269.         captureContext.putImageData(captureImageData, 0, 0);
  270.         return captureCanvas.toDataURL();
  271.     }
  272.  
  273.     function checkMotionPixel(motionPixels, x, y) {
  274.         return motionPixels && motionPixels[x] && motionPixels[x][y];
  275.     }
  276.  
  277.     function getPixelDiffThreshold() {
  278.         return pixelDiffThreshold;
  279.     }
  280.  
  281.     function setPixelDiffThreshold(val) {
  282.         pixelDiffThreshold = val;
  283.     }
  284.  
  285.     function getScoreThreshold() {
  286.         return scoreThreshold;
  287.     }
  288.  
  289.     function setScoreThreshold(val) {
  290.         scoreThreshold = val;
  291.     }
  292.  
  293.     return {
  294.         // public getters/setters
  295.         getPixelDiffThreshold: getPixelDiffThreshold,
  296.         setPixelDiffThreshold: setPixelDiffThreshold,
  297.         getScoreThreshold: getScoreThreshold,
  298.         setScoreThreshold: setScoreThreshold,
  299.  
  300.         // public functions
  301.         init: init,
  302.         start: start,
  303.         stop: stop
  304.     };
  305. })();
  306.         var video = document.getElementById('video');
  307. var canvas = document.getElementById('motion');
  308. var score = document.getElementById('score');
  309. var photo = document.getElementById('motion');
  310.  
  311. function initSuccess() {
  312.     DiffCamEngine.start();
  313. }
  314.  
  315. function initError() {
  316.     alert('Something went wrong.');
  317. }
  318. var ammount=0;
  319.   var majamm=0;
  320.   var large=0;
  321.   var vlarge=0;
  322.   var extreme=0;
  323.   var max=0;
  324.   var max1=0;
  325. function capture(payload) {
  326.  var p= photo.getContext('2d')
  327.     //score.textContent = payload.score;
  328.  oscillator.stop(0);
  329.                            if(payload.score>380000){
  330.                                      //alert(payload.score);
  331. var Message = new SpeechSynthesisUtterance("The Maximum Amount Of Movement Has Been Detected!!");
  332. var Voices = window.speechSynthesis.getVoices();
  333. Message.Voice = Voices[1];
  334. window.speechSynthesis.speak(Message);
  335.                                      max1++;
  336.       //alert(payload.score);
  337.       //alert('Super SUPER Large Amount Of Movement Detected!!');
  338.                        //majamm++;
  339.                      
  340. //photo.setAttribute('src',canvas.toDataUrl('image/png'));
  341.                        
  342.                         //window.open(captureImageData.ToDataURL());
  343.                         return;
  344.                        // p.putImage(captureImageData, 100, 100, 200, 200);
  345.                        }
  346.                                    if(payload.score>370000){
  347.                                      //alert(payload.score);
  348. var Message = new SpeechSynthesisUtterance("An Extremely Extremely Large Amount Of Movement Has Been Detected!!");
  349. var Voices = window.speechSynthesis.getVoices();
  350. Message.Voice = Voices[1];
  351. window.speechSynthesis.speak(Message);
  352.                                      max++;
  353.       //alert(payload.score);
  354.       //alert('Super SUPER Large Amount Of Movement Detected!!');
  355.                        //majamm++;
  356.                      
  357. //photo.setAttribute('src',canvas.toDataUrl('image/png'));
  358.                        
  359.                         //window.open(captureImageData.ToDataURL());
  360.                         return;
  361.                        // p.putImage(captureImageData, 100, 100, 200, 200);
  362.                        }
  363.                          
  364.                                    if(payload.score>210000){
  365.                                      //alert(payload.score);
  366. var Message = new SpeechSynthesisUtterance("An Extremely Large Amount Of Movement Has Been Detected!!");
  367. var Voices = window.speechSynthesis.getVoices();
  368. Message.Voice = Voices[1];
  369. window.speechSynthesis.speak(Message);
  370.                                      extreme++;
  371.       //alert(payload.score);
  372.       //alert('Super SUPER Large Amount Of Movement Detected!!');
  373.                        //majamm++;
  374.                      
  375. //photo.setAttribute('src',canvas.toDataUrl('image/png'));
  376.                        
  377.                         //window.open(captureImageData.ToDataURL());
  378.                         return;
  379.                        // p.putImage(captureImageData, 100, 100, 200, 200);
  380.                        }
  381.                                  if(payload.score>130000){
  382. var Message = new SpeechSynthesisUtterance("A Very Large Amount Of Movement Has Been Detected!!");
  383. var Voices = window.speechSynthesis.getVoices();
  384. Message.Voice = Voices[1];
  385. window.speechSynthesis.speak(Message);
  386.                                    vlarge++;
  387.       //alert(payload.score);
  388.       //alert('Super SUPER Large Amount Of Movement Detected!!');
  389.                        //majamm++;
  390.                      
  391. //photo.setAttribute('src',canvas.toDataUrl('image/png'));
  392.                        
  393.                         //window.open(captureImageData.ToDataURL());
  394.                         return;
  395.                        // p.putImage(captureImageData, 100, 100, 200, 200);
  396.                        }
  397.     if(payload.score>100000){
  398. var Message = new SpeechSynthesisUtterance("A Large Amount Of Movement Has Been Detected!!");
  399. var Voices = window.speechSynthesis.getVoices();
  400. Message.Voice = Voices[1];
  401. window.speechSynthesis.speak(Message);
  402.       large++
  403.       //alert(payload.score);
  404.       //alert('Super Large Amount Of Movement Detected!!');
  405.                        //majamm++;
  406.                      
  407. //photo.setAttribute('src',canvas.toDataUrl('image/png'));
  408.                        
  409.                         //window.open(captureImageData.ToDataURL());
  410.                         return;
  411.                        // p.putImage(captureImageData, 100, 100, 200, 200);
  412.                        }
  413.                    if(payload.score>115){score.textContent =('A Normal Amount Of Movement Has Been Detected '+majamm +' times!!')
  414.                        majamm++;
  415.                      
  416. //photo.setAttribute('src',canvas.toDataUrl('image/png'));
  417.                        
  418.                         //window.open(captureImageData.ToDataURL());
  419.                  //       return;
  420.                        // p.putImage(captureImageData, 100, 100, 200, 200);
  421.                        }
  422.   if(payload.score<35){}else{
  423.     //p.putImage(captureImageData, 100, 100, 200, 200);
  424.     console.log('Minor Movement Detected '+ammount+' times!!')
  425.     ammount++;
  426.     return;
  427.   }
  428. }
  429.  
  430. DiffCamEngine.init({
  431.     video: video,
  432.     motionCanvas: canvas,
  433.     initSuccessCallback: initSuccess,
  434.     initErrorCallback: initError,
  435.     captureCallback: capture
  436. });  
  437.           var context = new AudioContext();
  438. oscillator=context.createOscillator();
  439.           </script>
  440.          
  441.           <center>
  442. <body bgcolor="black">
  443. <font color="white">
  444. <canvas id="canvas" width="850" height="450"></canvas>
  445. <script>
  446. var canvas = document.getElementById("motion");
  447. var ctx = canvas.getContext("2d");
  448. var width=120
  449. ctx.fillStyle = "white";
  450. ctx.fillRect(0,0,120,1000);
  451. ctx.fillStyle = "blue";
  452. ctx.fillRect(0,400,120,100);
  453. ctx.fillStyle = "yellow";
  454. ctx.fillRect(width,0,120,1000);
  455. ctx.fillStyle = "magenta";
  456. ctx.fillRect(width,400,120,100);
  457. ctx.fillStyle = "cyan";
  458. ctx.fillRect(width*2,0,120,1000);
  459. ctx.fillStyle = "yellow";
  460. ctx.fillRect(width*2,400,120,100);
  461. ctx.fillStyle = "#0FFF00";
  462. ctx.fillRect(width*3,0,120,1000);
  463. ctx.fillStyle = "red";
  464. ctx.fillRect(width*3,400,120,100);
  465. ctx.fillStyle = "magenta";
  466. ctx.fillRect(width*4,0,120,1000);
  467. ctx.fillStyle = "cyan";
  468. ctx.fillRect(width*4,400,120,100);
  469. ctx.fillStyle = "red";
  470. ctx.fillRect(width*5,0,120,1000);
  471. ctx.fillStyle = "#0FFF00";
  472. ctx.fillRect(width*5,400,120,100);
  473. ctx.fillStyle = "blue";
  474. ctx.fillRect(width*6,0,120,1000);
  475. ctx.fillStyle = "white";
  476. ctx.fillRect(width*6,400,120,100);
  477.  
  478. oscillator.type = 'sine';
  479. oscillator.frequency.value = 1000;
  480. oscillator.connect(context.destination);
  481. oscillator.start(0);
  482. </script>
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top