index.html 2.91 KB
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display Webcam Stream</title>
 
<style>
#container {
	margin: 0px auto;
	width: 640px;
	height: 960px;
	border: 10px #333 solid;
}
#videoInput {
	width: 640px;
	height: 480px;
	background-color: #666;
}
#canvasOutput {
	width: 640px;
	height: 480px;
	background-color: #666;
}
</style>
<script type='text/javascript' src="{{url_for('static', filename='js/opencv.js')}}"></script>
<script type='text/javascript' src="{{url_for('static', filename='js/utils.js')}}"></script>
<script type='text/javascript'>
function main()
{
let video = document.getElementById("videoInput");
let canvasOutput = document.getElementById('canvasOutput');
let canvasContext = canvasOutput.getContext('2d');

if (navigator.mediaDevices.getUserMedia){
    navigator.mediaDevices.getUserMedia({ video: true })
	.then(function (stream) {
            video.srcObject = stream;
	}).catch(function (err0r) {
            console.log("Something went wrong!");
        });
}
let src = new cv.Mat(video.height, video.width, cv.CV_8UC4);
let dst = new cv.Mat(video.height, video.width, cv.CV_8UC4);
let gray = new cv.Mat();
let cap = new cv.VideoCapture(video);
let faces = new cv.RectVector();
let classifier = new cv.CascadeClassifier();
var streaming = true;

let utils = new Utils('errorMessage'); //use utils class
let faceCascadeFile = "/static/js/haarcascade_frontalface_default.xml"
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
    alert(faceCascadeFile);
    classifier.load(faceCascadeFile);
});
const FPS = 30;
function processVideo() {
    try {
        if (!streaming) {
            // clean and stop.
            src.delete();
            dst.delete();
            gray.delete();
            faces.delete();
            classifier.delete();
            return;
        }
        let begin = Date.now();
        // start processing.
        cap.read(src);
        src.copyTo(dst);
        cv.cvtColor(dst, gray, cv.COLOR_RGBA2GRAY, 0);
	alert('d');
        // detect faces.
        classifier.detectMultiScale(gray, faces, 1.1, 3, 0);
	alert('e');
        // draw faces.
        for (let i = 0; i < faces.size(); ++i) {
            let face = faces.get(i);
            let point1 = new cv.Point(face.x, face.y);
            let point2 = new cv.Point(face.x + face.width, face.y + face.height);
            cv.rectangle(dst, point1, point2, [255, 0, 0, 255]);
        }
	alert('f');
        cv.imshow('canvasOutput', dst);
        // schedule the next one.
        let delay = 1000/FPS - (Date.now() - begin);
        setTimeout(processVideo, delay);
    } catch (err) {
        console.log(err);
    }
}
setTimeout(processVideo, 0);
}
</script>
</head>
<body onload="cv['onRuntimeInitialized']=()=>{ main() }">
<div id="container">
<video autoplay="true" id="videoInput" width=640 height=480> <!-- style="visibility: hidden"-->

</video>
<canvas id='canvasOutput' width=640 height=480>

</canvas>
</div>
</body>
</html>