CoolFace
Apppublic

eaglelandsonce/TensorFlowJSClass

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
script2.js77 linesDownload Raw Back to root
1const video = document.getElementById('video');2const canvas = document.getElementById('output');3const ctx = canvas.getContext('2d');4 5async function setupCamera() {6    video.width = 640;7    video.height = 480;8 9    const stream = await navigator.mediaDevices.getUserMedia({10        video: true11    });12    video.srcObject = stream;13 14    return new Promise((resolve) => {15        video.onloadedmetadata = () => {16            resolve(video);17        };18    });19}20 21async function loadAndPredict() {22    const net = await posenet.load();23 24    async function detectPose() {25        const pose = await net.estimateSinglePose(video, {26            flipHorizontal: false27        });28 29        ctx.clearRect(0, 0, canvas.width, canvas.height);30        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);31        drawKeypoints(pose.keypoints, 0.6, ctx);32        drawSkeleton(pose.keypoints, 0.7, ctx);33 34        requestAnimationFrame(detectPose);35    }36 37    detectPose();38}39 40function drawKeypoints(keypoints, minConfidence, ctx) {41    keypoints.forEach((keypoint) => {42        if (keypoint.score >= minConfidence) {43            const { y, x } = keypoint.position;44            ctx.beginPath();45            ctx.arc(x, y, 5, 0, 2 * Math.PI);46            ctx.fillStyle = 'red';47            ctx.fill();48        }49    });50}51 52function drawSkeleton(keypoints, minConfidence, ctx) {53    const adjacentKeyPoints = posenet.getAdjacentKeyPoints(keypoints, minConfidence);54 55    adjacentKeyPoints.forEach((keypoints) => {56        drawSegment(keypoints[0].position, keypoints[1].position, ctx);57    });58}59 60function drawSegment({ y: y1, x: x1 }, { y: y2, x: x2 }, ctx) {61    ctx.beginPath();62    ctx.moveTo(x1, y1);63    ctx.lineTo(x2, y2);64    ctx.lineWidth = 2;65    ctx.strokeStyle = 'green';66    ctx.stroke();67}68 69setupCamera().then((video) => {70    video.play();71    video.onplay = () => {72        canvas.width = video.width;73        canvas.height = video.height;74        loadAndPredict();75    };76});77