File size: 1,931 Bytes
c01955c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html>
<body>

<h2>Live Face Detection</h2>

<video id="video" autoplay playsinline></video>
<canvas id="canvas"></canvas>

<script>
const ws = new WebSocket("ws://localhost:7836/api/face/findFace");

const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

ws.onopen = () => console.log("βœ… Connected");
ws.onclose = (e) => {
    console.log("❌ Disconnected", e.code, e.reason);
    clearInterval(sendInterval);
};
ws.onerror = (e) => console.error("πŸ”₯ WebSocket Error", e);

// πŸŽ₯ Start webcam
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
    video.srcObject = stream;
});

// πŸ” Send frames continuously
const sendInterval = setInterval(() => {
    if (ws.readyState !== WebSocket.OPEN) return;
    if (video.videoWidth === 0) return;

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;

    ctx.drawImage(video, 0, 0);

    canvas.toBlob(blob => {
        blob.arrayBuffer().then(buffer => {
            if (ws.readyState === WebSocket.OPEN) {
                ws.send(buffer); // πŸ”₯ binary send
            }
        });
    }, "image/jpeg", 0.7); // compress for speed

}, 100); // ⚑ 10 FPS

// πŸ“© Receive result
ws.onmessage = (event) => {
    const data = JSON.parse(event.data);

    if (data.is_error) {
        console.error("Server Error:", data.error_message);
        return;
    }

    if (!data.data || !data.data.relative_bounding_box) return;

    const bbox = data.data.relative_bounding_box;

    const x = bbox.xmin * canvas.width;
    const y = bbox.ymin * canvas.height;
    const w = bbox.width * canvas.width;
    const h = bbox.height * canvas.height;

    // Draw video frame again
    ctx.drawImage(video, 0, 0);

    // Draw box
    ctx.strokeStyle = "red";
    ctx.lineWidth = 3;
    ctx.strokeRect(x, y, w, h);
};
</script>

</body>
</html>