Day twenty five: beardify

October 20, 2015

Brace yourself. No shave November is coming! To help you decide wether you look awesome with epic facial hair. Use today’s app. Make room for Beardify!

live demo

Today is all about beards. Beards are lovely. A well groomed beard can tell a lot about a person. However, for the unfortunate among us that can’t grow the most epic of facial hair. There is a solution to all beard growing related problems! Beardify places a beard on your face through your webcam!

preview

How it works

Beardify uses the facial recognition library called trackingjs. When the user turns on the webcam. The camera is used to find the dimension of the face and with the help of an overlaying canvas. Paints a beard over the video. Let’s break this down.

facial recognition

Using trackingjs this was a breeze. First we create an object tracker. We pass the object we want to track which in this case is the face.

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

We now can initiate the tracking of a face object. Let’s bind it to a video DOM element and start using the camera!

tracking.track('#myVideo', tracker, {
      camera: true
    });

So far so good! To get the beard on the screen I added a bit of trickery. As mentioned before. The video is nothing more than what the camera can see. The app isn’t going to manipulate that. However, to place the beard on the video I placed a canvas over the video DOM element. Let’s have a look at how this looks like.

placing the beard

Turns out we can listen to events fired by the tracker. Listening to this event assures us that we always have the dimensions of the face.

tracker.on('track', function (e) {
    if (e.data.length > 0) {
      e.data.forEach(function (rect) {
        context.clearRect(0, 0, canvas.width, canvas.height);
        var image = new Image();
        image.src = '/images/beard.png';
        var y = rect.y + (rect.height / 2);
        context.drawImage(image, rect.x, y, rect.width, rect.height);
      });
    }
  });

Oh my! That’s a lot of code! Fear not, my dear reader. It’s actually really simple.

The track event gets fired every time a change occurs. This is usually because the user moves. When the tracking can’t detect a face. We do nothing. Otherwise we grab the canvas and the beard image. The beard gets placed on the bottom half of the face and gets the width and height of the user’s face. That’s it! Now everyone can be the manliest of man with Beardify! Yes, even you ladies.

Thank you for reading and leave a star on the repo.

Comments