how to capture image after face detection in tracking js

后端 未结 1 1906
萌比男神i
萌比男神i 2021-01-13 18:56

I am using tracking js for face detection. I successfully detected the face but I don\'t know how to capture image frame.I want to save the detected face as image. This is m

相关标签:
1条回答
  • 2021-01-13 19:26

    You could use getUserMedia api and use download attribute on <a> element. It's a bit tricky and it will not be available on all browsers:

    First draw the video on canvas:

    tracker.on('track', function(event) {
      context.clearRect(0, 0, canvas.width, canvas.height);
      event.data.forEach(function(rect) {
        context.strokeStyle = '#ff0000';
        context.strokeRect(rect.x, rect.y, rect.width, rect.height);
        context.font = '11px Helvetica';
        context.fillStyle = "#fff";
        context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
        context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
        context.drawImage(video, rect.x, rect.y, rect.width, rect.height, rect.x, rect.y, rect.width, rect.height);
      });
    });
    

    Create a method to trigger the snapshot:

    var snapshot = function() {
      if (localMediaStream) {
        document.querySelector('a').href = canvas.toDataURL('image/webp');
      }
    }
    
    video.addEventListener('click', snapshot, false);
    

    Keep a reference to user media:

    navigator.getUserMedia({video: true}, function(stream) {
      localMediaStream = stream;
    }, function(error){console.error(error)});
    

    See a rough demo with all the code in action here. Click on the video and a image should be saved (Note: Using latest Chrome; You may need to fine tune coordinates; Be sure to click snapshot after detection was done correctly).

    0 讨论(0)
提交回复
热议问题