Search code examples
javascriptcanvasface-recognitiontracking.js

Face tracking on canvas via tracking.js


tracking.js makes it fairly easy to detect a face on an <img>. They have a wonderful hello world example for this, but I was wondering if anyone figured out yet how to detect a face on a <canvas> element.

I tried:

var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
img = img = context.getImageData(0, 0, canvas.width, canvas.height);

var tracker = new tracking.ObjectTracker(['face']);
tracker.setStepSize(1.7);

tracking.track('#canvas', tracker);

tracker.on('track', function(event) {
    event.data.forEach(function(rect) {
    window.plot(rect.x, rect.y, rect.width, rect.height);
    });
});

window.plot = function(x, y, w, h) {
    var rect = document.createElement('div');
    document.querySelector('#preview').appendChild(rect);
    rect.classList.add('rect');
    rect.style.width = w + 'px';
    rect.style.height = h + 'px';
    rect.style.left = (img.offsetLeft + x) + 'px';
    rect.style.top = (img.offsetTop + y) + 'px';
    rect.style.borderColor = '#ff0000';
};

Nothing happens :-/


Solution

  • I had the same issue. Just change the order. Put tracking.track('#canvas', tracker) behind the tracker.on - section and it should work.

    But if you want to "highlight" it on a canvas you should draw at the context instead of plotting. You can also pass the imageData directly tracker.track(imgData, width, height)... Have fun.