javascript - 如何让 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,但这也没有用。
我的代码中是否缺少某些内容,或者有其他方法可以解决这个问题?
谢谢!
解决方案
推荐阅读
- c# - 无法在下拉列表中选择要选择的 SelectList 项
- git - 以前的 git bisect “会话”的状态是否存储在 git 的某个地方?
- python - Python Cerberus - 如果另一个不存在则需要一个
- latex - 如何将命令 zhnumber 替换为在 Latex 中添加英文数字的等效命令
- ethernet - 2 台设备如何通过以太网交换机进行通信
- javascript - 元素/值的每个更改列表上的 JavaScript 计数器为零(从零开始)
- flutter - 在颤动的输入字段上键入时如何更改文本字段
- ios - 如何将与现实世界对象的碰撞应用到 RealityKit 中的 3D 对象 (.usdz)?
- laravel - Laravel:电子邮件未从服务器发送
- java - Java PriorityQueue Comparator 在特定条件下插入二维数组