首页 > 解决方案 > 如何让 runDetection 每 2 秒运行一次?

问题描述

JS:

const video = document.getElementById("myvideo");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
let trackButton = document.getElementById("trackbutton");
let updateNote = document.getElementById("updatenote");

let isVideo = false;
let model = null;

let headers = new Headers();

headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');

headers.append('Access-Control-Allow-Origin', 'http://127.0.0.1:8080');
headers.append('Access-Control-Allow-Credentials', 'true');

const modelParams = {
    flipHorizontal: true,   // flip e.g for video  
    maxNumBoxes: 20,        // maximum number of boxes to detect
    iouThreshold: 0.5,      // ioU threshold for non-max suppression
    scoreThreshold: 0.6,    // confidence threshold for predictions.
    modelType: "ssd320fpnlite",
    bboxLineWidth: "2",
    fontSize: 17,
}

function startVideo() {
    handTrack.startVideo(video).then(function (status) {
        console.log("video started", status);
        if (status) {
            updateNote.innerText = "Video started. Now tracking"
            isVideo = true
            setInterval(runDetection, 3000)
        } else {
            updateNote.innerText = "Please enable video"
        }
    });
}

function toggleVideo() {
    if (!isVideo) {
        updateNote.innerText = "Starting video"
        startVideo();
    } else {
        updateNote.innerText = "Stopping video"
        handTrack.stopVideo(video)
        isVideo = false;
        updateNote.innerText = "Video stopped"
    }
}



function runDetection() {
    model.detect(video).then(predictions => {
        console.log(predictions);
        if(predictions.length !==0){
            let label = predictions[0].label;
            let score = predictions[0].score;
            console.log(`Label: ${label}\nScore: ${score}`);
                if (label == "closed") {
                    console.log("Closed");
                } else {
                    console.log("Not Closed");
                }
        }
        model.renderPredictions(predictions, canvas, context, video);
        if (isVideo) {
            setInterval(requestAnimationFrame(runDetection), 3000);
        }
    });
}

// Load the model.
handTrack.load(modelParams).then(lmodel => {
    // detect objects in the image.
    model = lmodel
    updateNote.innerText = "Loaded Model!"
    trackButton.disabled = false
});


这是 HandTrack.js

我尝试使用 setInterval() 但它仍然会非常频繁地运行检测,而不是每 2 秒运行一次。如果我的手是闭合的,我希望它每两秒打印一次“Closed”,但是使用 setInterval() 不起作用。我什至尝试使用 setTimeout,但这也没有用。

我的代码中是否缺少某些内容,或者有其他方法可以解决这个问题?

谢谢!

标签: javascript

解决方案


推荐阅读