当面数超过两个时触发事件
Posted
技术标签:
【中文标题】当面数超过两个时触发事件【英文标题】:Fire an event when number of face more than two 【发布时间】:2020-10-11 19:44:37 【问题描述】:这是我使用 javascript API 进行人脸检测的代码。 当我检测到两个以上的面孔时,我想添加一个条件,然后做一些事情。 我想在 Chrome 浏览器上创建一个扩展,但我不知道如何在我的代码中添加这个条件
const video = document.getElementById("video");
let predictedAges = [];
Promise.all([
faceapi.nets.tinyFaceDetector.loadFromUri("/models"),
faceapi.nets.faceLandmark68Net.loadFromUri("/models"),
faceapi.nets.faceRecognitionNet.loadFromUri("/models"),
faceapi.nets.faceExpressionNet.loadFromUri("/models"),
faceapi.nets.ageGenderNet.loadFromUri("/models")
]).then(startVideo);
function startVideo()
navigator.getUserMedia(
video: ,
stream => (video.srcObject = stream),
err => console.error(err)
);
video.addEventListener("playing", () =>
const canvas = faceapi.createCanvasFromMedia(video);
document.body.append(canvas);
const displaySize = width: video.width, height: video.height ;
faceapi.matchDimensions(canvas, displaySize);
setInterval(async () =>
const detections = await faceapi
.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())
.withFaceLandmarks()
.withFaceExpressions()
.withAgeAndGender();
const resizedDetections = faceapi.resizeResults(detections, displaySize);
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
faceapi.draw.drawDetections(canvas, resizedDetections);
faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);
faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
const age = resizedDetections[0].age;
const interpolatedAge = interpolateAgePredictions(age);
const bottomRight =
x: resizedDetections[0].detection.box.bottomRight.x - 50,
y: resizedDetections[0].detection.box.bottomRight.y
;
new faceapi.draw.DrawTextField(
[`$faceapi.utils.round(interpolatedAge, 0) years`],
bottomRight
).draw(canvas);
, 100);
);
function interpolateAgePredictions(age)
predictedAges = [age].concat(predictedAges).slice(0, 30);
const avgPredictedAge =
predictedAges.reduce((total, a) => total + a) / predictedAges.length;
return avgPredictedAge;
【问题讨论】:
【参考方案1】:为了回答这个问题,我终于通过使用检测对象的属性找到了解决方案
获取我正在使用的识别中检测到的人脸数量
detections.length
问题解决了!!
if(detections.length>=2) 做点什么!!
【讨论】:
以上是关于当面数超过两个时触发事件的主要内容,如果未能解决你的问题,请参考以下文章
iOS 利用运行时交换系统方法实现禁止同时点击两个按钮触发多个事件