Video 動き検出

<!DOCTYPE html>
<html lang=”en”>

<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<title>Document</title>
<link rel=”stylesheet” href=”main.css” type=”text/css”>
</head>

<body>
<script language=”javascript”>

function stopVideo() {
console.log(“stopVideo()”)
document.getElementById(‘video’).pause();
}
function resumeVideo() {
console.log(“resumeVideo()”)
document.getElementById(‘video’).play();
}
function startVideo() {
var video = document.getElementById(‘video’);

navigator.mediaDevices.getUserMedia({ audio: true, video: { facingMode: “user” } })
.then(stream => video.srcObject = stream)
.catch(err => console.log(err.name + “: ” + err.message));
}
function diffVideo() {
var video = document.getElementById(“video”);
var prevImage = new Image;

setInterval(function () {
var canvas1 = document.getElementById(“canvas1”);
var ctx1 = canvas1.getContext(“2d”);

var canvas2 = document.getElementById(“canvas2”);
var ctx2 = canvas2.getContext(“2d”);

var canvasDiff = document.getElementById(“canvasDiff”);
var ctxDiff = canvasDiff.getContext(“2d”);

var img1 = ctx1.getImageData(0, 0, canvas1.width, canvas1.height); // 1をimg1へ
ctx2.putImageData(img1, 0, 0); // 1をcanvas2へ
ctx1.drawImage(video, 0, 0, canvas1.width, canvas1.height); // video を1へ
img1 = ctx1.getImageData(0, 0, canvas1.width, canvas1.height); // 1をimg1へ
var img2 = ctx2.getImageData(0, 0, canvas2.width, canvas2.height); // 2をimg2へ

var dst = ctxDiff.createImageData(canvasDiff.width, canvasDiff.height);

for (var i = 0; i < img1.data.length; i = i + 4) {
var f1 = ~~((img1.data[i] + img1.data[i + 1] + img1.data[i + 2]) / 3);
var f2 = ~~((img2.data[i] + img2.data[i + 1] + img2.data[i + 2]) / 3);
var d = Math.abs(f2 – f1) > 40 ? 255 : 0;
dst.data[i] = dst.data[i + 1] = dst.data[i + 2] = d;
dst.data[i + 3] = img1.data[i + 3];
}

ctxDiff.putImageData(dst, 0, 0);
}, 1000 / 30);
}
</script>

<h1 id=”msg”>Camera 動き検出</h1>

<div>
<video id=”video” autoplay></video>
</div>
<div>
<button onClick=”startVideo()”>Start Video</button>
</div>
<div>
<button onClick=”diffVideo()”>Diff Video</button>
</div>

<div>
<canvas id=”canvas1″></canvas>
</div>

<div>
<canvas id=”canvas2″></canvas>
</div>

<div>
<canvas id=”canvasDiff”></canvas>
</div>
</body>

</html>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です