-
Notifications
You must be signed in to change notification settings - Fork 13
/
camera.html
85 lines (80 loc) · 2.14 KB
/
camera.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<!doctype html>
<html>
<head>
<title>OpenCV Video Examples - Camera</title>
<link href="app.css" rel="stylesheet">
</head>
<body>
<h1>OpenCV Camera</h1>
<div>
<button id="actionBtn">Start</button>
</div>
<video id="video" width="300" height="225"></video>
<canvas id="canvasOutput"></canvas>
<script async src="opencv.js" type="text/javascript" onload="onCvLoaded();"></script>
<script>
function onCvLoaded () {
console.log('cv', cv);
cv.onRuntimeInitialized = onReady;
}
const video = document.getElementById('video');
const actionBtn = document.getElementById('actionBtn');
const width = 300;
const height = 225;
const FPS = 30;
let stream;
let streaming = false;
function onReady () {
let src;
let dst;
const cap = new cv.VideoCapture(video);
actionBtn.addEventListener('click', () => {
if (streaming) {
stop();
actionBtn.textContent = 'Start';
} else {
start();
actionBtn.textContent = 'Stop';
}
});
function start () {
navigator.mediaDevices.getUserMedia({ video: true, audio: false })
.then(_stream => {
stream = _stream;
console.log('stream', stream);
video.srcObject = stream;
video.play();
streaming = true;
src = new cv.Mat(height, width, cv.CV_8UC4);
dst = new cv.Mat(height, width, cv.CV_8UC1);
setTimeout(processVideo, 0)
})
.catch(err => console.log(`An error occurred: ${err}`));
}
function stop () {
if (video) {
video.pause();
video.srcObject = null;
}
if (stream) {
stream.getVideoTracks()[0].stop();
}
streaming = false;
}
function processVideo () {
if (!streaming) {
src.delete();
dst.delete();
return;
}
const begin = Date.now();
cap.read(src)
cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY);
cv.imshow('canvasOutput', dst);
const delay = 1000/FPS - (Date.now() - begin);
setTimeout(processVideo, delay);
}
}
</script>
</body>
</html>