我正在使用视频流,然后从视频流中获取一个片段作为图像放置在随该流而变化的画布中。 但是,当我尝试获取该画布的ImageData时,它的值是“ 0”。
下面是代码段:
var EYEElement = document.getElementById("eyes");
const ctx = EYEElement.getContext("2d");
const ImageData = ctx.getImageData(70, 0, 70, 25);
这是我的网络摄像头代码,并从视频元素分配画布图像。
EyeTracking = async () => {
//initialize the webcam stream
const video = $('#webcam')[0];
//initilization of the clmTracker
const ctrack = new clm.tracker();
ctrack.init();
async function trackingLoop() {
// Check if a face is detected, and if so, track it.
requestAnimationFrame(trackingLoop);
let currentPosition = ctrack.getCurrentPosition();
overlayCC.clearRect(0, 0, 400, 300);
if (currentPosition) {
// Draw facial mask on overlay canvas:
ctrack.draw(overlay);
// Get the eyes rectangle and draw it in red:
const eyesRect = getEyesRectangle(currentPosition);
overlayCC.strokeStyle = 'red';
overlayCC.strokeRect(eyesRect[0], eyesRect[1], eyesRect[2], eyesRect[3]);
// The video might internally have a different size, so we need these
// factors to rescale the eyes rectangle before cropping:
const resizeFactorX = video.videoWidth / video.width;
const resizeFactorY = video.videoHeight / video.height;
// Crop the eyes from the video and paste them in the eyes canvas:
const eyesCanvas = $('#eyes')[0];
//console.log(eyesCanvas);
const eyesCC = eyesCanvas.getContext('2d');
//
//eyeContext=eyeCC;
await eyesCC.drawImage(
video,
eyesRect[0] * resizeFactorX, eyesRect[1] * resizeFactorY,
eyesRect[2] * resizeFactorX, eyesRect[3] * resizeFactorY,
0, 0, eyesCanvas.width, eyesCanvas.height
);
console.log(eyesCC.getImageData(70, 0, eyesCanvas.width, eyesCanvas.height));
}
}
//canvas overlay work
const overlay = $('#overlay')[0];
const overlayCC = overlay.getContext('2d');
//function to apply the stream to video element of html
function onStreaming(stream) {
//start video stream
video.srcObject = stream;
//start tracking stream using clmtrackr
ctrack.start(video);
//add a loop of green color around the face
trackingLoop();
}
navigator.mediaDevices.getUserMedia({ video: true }).then(onStreaming);
document.onmousemove = mouse.handleMouseMove;
}