(Faster) Facial landmark detector with dlib

Back in September 2017, Davis King released v19.7 of dlib — and inside the release notes you’ll find a short, inconspicuous bullet point on dlib’s new 5-point facial landmark detector:

  • Added a 5 point face landmarking model that is over 10x smaller than the 68 point model, runs faster, and works with both HOG and CNN generated face detections.

My goal here today is to introduce you to the new dlib facial landmark detector which is faster (by 8-10%), more efficient, and smaller (by a factor of 10x) than the original version.

Inside the rest of today’s blog post we’ll be discussing dlib’s new facial landmark detector, including:

  • How the 5-point facial landmark detector works
  • Considerations when choosing between the new 5-point version or the original 68-point facial landmark detector for your own applications
  • How to implement the 5-point facial landmark detector in your own scripts
  • A demo of the 5-point facial landmark detector in action

To learn more about facial landmark detection with dlib, just keep reading.

Looking for the source code to this post?
Jump right to the downloads section.

(Faster) Facial landmark detector with dlib

In the first part of this blog post we’ll discuss dlib’s new, faster, smaller 5-point facial landmark detector and compare it to the original 68-point facial landmark detector that was distributed with the the library.

From there we’ll implement facial landmark detection using Python, dlib, and OpenCV, followed by running it and viewing the results.

Finally, we’ll discuss some of the limitations of using a 5-point facial landmark detector and highlight some of the scenarios in which you should be using the 68-point facial landmark detector of the 5-point version.

Dlib’s 5-point facial landmark detector

Figure 1: A comparison of the dlib 68-point facial landmarks (top) and the 5-point facial landmarks (bottom).

Figure 1 above visualizes the difference between dlib’s new 5-point facial landmark detector versus the original 68-point detector.

While the 68-point detector localizes regions along the eyes, eyebrows, nose, mouth, and jawline, the 5-point facial landmark detector reduces this information to:

  • 2 points for the left eye
  • 2 points for the right eye
  • 1 point for the nose

The most appropriate use case for the 5-point facial landmark detector is face alignment.

In terms of speedup, I found the new 5-point detector to be 8-10% faster than the original version, but the real win here is model size: 9.2MB versus 99.7MB, respectively (over 10x smaller).

It’s also important to note that facial landmark detectors tend to be very fast to begin with (especially if they are implemented correctly, as they are in dlib).

The real win in terms of speedup will be to determine which face detector you should use. Some face detectors are faster (but potentially less accurate) than others. If you remember back to our drowsiness detection series:

You’ll recall that we used the more accurate HOG + Linear SVM face detector for the laptop/desktop implementation, but required a less accurate but faster Haar cascade to achieve real-time speed on the Raspberry Pi.

In general, you’ll find the following guidelines to be a good starting point when choosing a face detection model:

  • Haar cascades: Fast, but less accurate. Can be a pain to tune parameters.
  • HOG + Linear SVM: Typically (significantly) more accurate than Haar cascades with less false positives. Normally less parameters to tune at test time. Can be slow compared to Haar cascades.
  • Deep learning-based detectors: Significantly more accurate and robust than Haar cascades and HOG + Linear SVM when trained correctly. Can be very slow depending on depth and complexity of model. Can be sped up by performing inference on GPU (you can see an OpenCV deep learning face detector in this post).

Keep these guidelines in mind when building your own applications that leverage both face detection and facial landmarks.

Implementing facial landmarks with dlib, OpenCV, and Python

Now that we have discussed dlib’s 5-point facial landmark detector, let’s write some code to demonstrate and see it in action.

Open up a new file, name it faster_facial_landmarks.py , and insert the following code:

On Lines 2-8 we import necessary packages, notably dlib  and two modules from imutils .

The imutils package has been updated to handle both the 68-point and 5-point facial landmark models. Ensure that you upgrade it in your environment via:

Again, updating imutils will allow you to work with both 68-point and 5-point facial landmarks.

From there, let’s parse command line arguments:

We have one command line argument: --shape-predictor . This argument allows us to change the path to the facial landmark predictor that will be loaded at runtime.

Note: Confused about command line arguments? Be sure to check out my recent post where command line arguments are covered in depth.

Next, let’s load the shape predictor and initialize our video stream:

On Lines 19 and 20, we initialize dlib’s pre-trained HOG + Linear SVM face detector  and load the shape_predictor  file.

In order to access the camera, we’ll be using the VideoStream  class from imutils.

You can select (via commenting/uncommenting Lines 25 and 26) whether you’ll use a:

  1. Built-in/USB webcam
  2. Or if you’ll be using a PiCamera on your Raspberry Pi

From there, let’s loop over the frames and do some work:

First, we read a frame  from the video stream, resize it, and convert to grayscale (Lines 34-36).

Then let’s use our HOG + Linear SVM  detector  to detect faces in the grayscale image (Line 39).

From there, we draw the total number of faces in the image on the original frame by first making sure that at least one face was detected (Lines 43-46).

Next, let’s loop over the face detections and draw the landmarks:

Beginning on Line 49, we loop over the faces in rects .

We draw the face bounding box on the original frame (Lines 52-54), by using our face_utils  module from imutils (which you can read more about here).

Then we pass the face to predictor  to determine the facial landmarks (Line 59) and subsequently we convert the facial landmark coordinates to a NumPy array.

Now here’s the fun part. To visualize the landmarks, we’re going to draw tiny dots using cv2.circle and number each of the coordinates.

On Line 64, we loop over the landmark coordinates. Then we draw a small filled-in circle as well as the landmark number on the original frame .

Let’s finish our facial landmark script out:

In this block, we display the frame (Line 70), break out of the loop if “q” is pressed (Lines 71-75), and perform cleanup (Lines 78 and 79).

Running our facial landmark detector

Now that we have implemented our facial landmark detector, let’s test it out.

Be sure to scroll down to the “Downloads” section of this blog post to download the source code and 5-point facial landmark detector.

From there, open up a shell and execute the following command:

Figure 2: The dlib 5-point facial landmark detector in action.

As you can see from the GIF above, we have successfully localized the 5 facial landmarks, including:

  • 2 points for the left eye
  • 2 points for the right eye
  • 1 point for the bottom of the nose

I have included a longer demonstration of the facial landmark detector in the video below:

Is dlib’s 5-point or 68-point facial landmark detector faster?

In my own tests I found that dlib’s 5-point facial landmark detector is 8-10% faster than the original 68-point facial landmark detector.

A 8-10% speed up is significant; however, what’s more important here is the size of the model.

The original 68-point facial landmark is nearly 100MB, weighing in at 99.7MB.

The 5-point facial landmark detector is under 10MB, at only 9.2MB — this is over a 10x smaller model!

When you’re building your own applications that utilize facial landmarks, you now have a substantially smaller model file to distribute with the rest of your app.

A smaller model size is nothing to scoff at either — just think of the reduced download time/resources for mobile app users!

Limitations of the 5-point facial landmark detector

The primary usage of the 5-point facial landmark detector will be face alignment:

Figure 3: Face alignment applied to obtain a canonical rotation of an input face.

For face alignment, the 5-point facial landmark detector can be considered a drop-in replacement for the 68-point detector — the same general algorithm applies:

  1. Compute the 5-point facial landmarks
  2. Compute the center of each eye based on the two landmarks for each eye, respectively
  3. Compute the angle between the eye centroids by utilizing the midpoint between the eyes
  4. Obtain a canonical alignment of the face by applying an affine transformation

While the 68-point facial landmark detector may give us slightly better approximation to the eye centers, in practice you’ll find that the 5-point facial landmark detector works just as well.

All that said, while the 5-point facial landmark detector is certainly smaller (9.2MB versus 99.7MB, respectively), it cannot be used in all situations.

A great example of such a situation is drowsiness detection:

Figure 4: We make use of dlib to calculate the facial landmarks + Eye Aspect Ratio (EAR) which in turn can alert us for drowsiness.

When applying drowsiness detection we need to compute the Eye Aspect Ratio (EAR) which is the ratio of the eye landmark width to the eye landmark height.

When using the 68-point facial landmark detector we have six points per eye, enabling us to perform this computation.

However, with the 5-point facial landmark detector we only have two points per eye (essentially p_{1} and p_{4} from Figure 4 above) — this is not enough enough to compute the eye aspect ratio.

If your plan is to build a drowsiness detector or any other application that requires more points along the face, including facial landmarks along the:

  • Eyes
  • Eyebrows
  • Nose
  • Mouth
  • Jawline

…then you’ll want to use the 68-point facial landmark detector instead of the 5-point one.

Interested in learning from Davis King, author of dlib and CV/ML expert?

If you’re interested in learning from Davis King and other computer vision + deep learning experts, then look no further than PyImageConf, PyImageSearch’s very own practical, hands-on computer vision and deep learning conference.

At PyImageConf on August 26-28th in San Francisco, CA, you’ll be able to attend talks and workshops by 10+ prominent speakers and workshop hosts, including Davis King, Francois Chollet (AI researcher at Google and author of Keras), Katherine Scott (SimpleCV and PlanetLabs), Agustín Azzinnari + Alan Descoins (Faster R-CNN and object detection experts at TryoLabs), myself, and more! 

You should plan to attend if you:

  • Are eager to learn from top educators in the field
  • Are a working for a large company and are thinking of spearheading a computer vision product or app
  • Are an entrepreneur who is ready to ride the computer vision and deep learning wave
  • Are a student looking to make connections to help you both now with your research and in the near future to secure a job
  • Enjoy PyImageSearch’s blog and community and are ready to further develop relationships with live training

I guarantee you’ll be more than happy with your investment in time and resources attending PyImageConf — the talks and workshops will pay huge dividends on your own computer vision + deep learning projects.

To learn more about the conference, you can read the formal announcement here.

And from there, you can use the following link to grab your ticket!


In today’s blog post we discussed dlib’s new, faster, more compact 5-point facial landmark detector.

This 5-point facial landmark detector can be considered a drop-in replacement for the 68-point landmark detector originally distributed with the dlib library.

After discussing the differences between the two facial landmark detectors, I then provided an example script of applying the 5-point version to detect the eye and nose region of my face.

In my tests, I found the 5-point facial landmark detector to be 8-10% faster than the 68-point version while being 10x smaller.

To download the source code + 5-point facial landmark detector used in this post, just enter your email address in the form below — I’ll also be sure to email you when new computer vision tutorials are published here on the PyImageSearch blog.


If you would like to download the code and images used in this post, please enter your email address in the form below. Not only will you get a .zip of the code, I’ll also send you a FREE 11-page Resource Guide on Computer Vision and Image Search Engines, including exclusive techniques that I don’t post on this blog! Sound good? If so, enter your email address and I’ll send you the code immediately!

, , , , , , ,

30 Responses to (Faster) Facial landmark detector with dlib

  1. Gregory D'Seas April 2, 2018 at 11:32 am #

    Is there a group or a forum to bounce ideas related to work related to Python visual detectors related to your courses?


    • Adrian Rosebrock April 2, 2018 at 12:51 pm #

      The PyImageSearch Gurus course includes dedicated forums. Many readers inside the course are interested in and/or actively working with visual detectors.

      Additionally, the Deep Learning for Computer Vision with Python book includes a private companion site along with issue/bug trackers that readers utilize to converse.

      For your particular question though, I believe the Gurus course is what you would want.

  2. JBeale April 2, 2018 at 11:59 am #

    Your last sentence says “…10x faster.” but I think you mean 10x smaller.

    • Adrian Rosebrock April 2, 2018 at 12:49 pm #

      Thanks, you’re absolutely correct. I have updated the post.

  3. Ben April 2, 2018 at 1:12 pm #

    Hi, great article! I was wondering is there a way do this with kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange (420v) pixel format type instead of BGRA? I want to try it in my iOS objc live video chat app, which supports only the YUV format type.

    • Adrian Rosebrock April 2, 2018 at 5:05 pm #

      Could you just convert the frame from YUV to RGB instead? Sorry, I don’t have too much experience with Obj-C and iOS for this.

  4. Mansoor Nasir April 2, 2018 at 1:15 pm #

    Great post as always…

    I was wondering if we could use it as head pose estimation in real-time.

    Thank you.

    • Adrian Rosebrock April 2, 2018 at 5:07 pm #

      Technically sure, but it wouldn’t be as accurate. A good head pose estimation should consider the “boundary points” of the face, including outer corners of the eyes, mouth, and bottom of the chin. Keep in mind that the 5-point model gives only the eyes and nose. You would thus be estimating the pose with only 3 points (outer eye coordinates and nose).

  5. Majid April 2, 2018 at 5:03 pm #

    Hi Adrian,

    thanks for the interesting point. Regarding drowsiness detection, the current 68-point model is not accurate when the head is turned or using glasses or using IR camera. Do you have any suggestion on this?
    I have tried other face detection algorithms using deep learning methods which resulted in a better and faster face detection. However, when it comes to facial landmark detection still, I am lacking accuracy and speed.

    I have implemented your code in Raspberry pi resulting in a slow and erroneous performance.


    • Adrian Rosebrock April 2, 2018 at 5:10 pm #

      Keep in mind the following rules:

      1. If you cannot detect the face, you cannot detect the facial landmarks
      2. If you cannot detect the facial landmarks, you cannot use them for drowsiness detection

      Computer vision and deep learning models are not magic. If a head is too far rotated or the eyes not visible, you won’t be able to detect the face and compute the facial landmarks.

      Drowsiness is more than just vision-based, it can also be determined by other sensors, such as breathing, blood flow, etc. A drowsiness detector should involve multiple sensors, not just vision. Vision is one component of many that should be used.

      If you want to continue to use a vision-based approach, you can, but you’ll want to train some machine learning models to detect drowsiness from movements of the head, such as head bobs, tilting, etc. However, the Raspberry Pi will likely not be fast enough for this. Again, this is where multiple sensors would be useful.

  6. adam or April 3, 2018 at 11:18 am #

    Hi Adrian, thanks for the interesting material.
    I would like to ask something that may be a bit out of context.
    The packages involved here are pretty much complicated, in relation to versioning and installation requirements. If you can, please add a chapter on which packages to install and how to install them. I know there are multiple ways to install these packages,however if you could publish your method, then it would prove useful for many of us and shorten the time of practice.
    Many thanks to your true efforts.

    • Adrian Rosebrock April 3, 2018 at 4:48 pm #

      Which packages are you referring to? OpenCV is the main one that’s a bit of a pain to install. Dlib is now pretty straightforward to install. See my latest post on installing dlib.

      I don’t have any plans to add install tutorials to any of my books as I link to install instructions (on the PyImageSearch blog) from them. The main reason I do this is to ensure I can keep all install instructions up to date and release new install instructions when they change dramatically. Trying to keep install instructions in the book itself would lead to them being out of date and running into issues.

  7. adam or April 3, 2018 at 11:20 am #

    Hi Adrian,
    The frame i get from the streamer is None.
    Can you please assist?

    • Adrian Rosebrock April 3, 2018 at 4:46 pm #

      It sounds like OpenCV cannot access your camera. Are you using a USB webcam or Raspberry Pi camera module? I would suggest you take a look at this post to help diagnose further.

  8. Wisgon April 4, 2018 at 2:35 am #

    Hi, Adrian,

    I’m working with a great face_recognition system, and the process is face detect, 5 points alignment, then face recognition. But I find that the 5 points it wants is one point on the middle for each eye, one point for nose, and two points for the mouth on the left side and right side. So it’s different from the 5 point you demonstrated in this article, so I want to ask can this module output the 5 points I want?

    • Adrian Rosebrock April 4, 2018 at 12:06 pm #

      Traditional face alignment is done using the eye centers and the midpoint of the eyes. Calculate those values and you should be able to perform face alignment.

  9. Girija April 5, 2018 at 7:18 am #

    Hi, Adrian
    Can you please tell me, what are the inputs for the Dlib’s 5-point landmark detector to the FACIAL_LANDMARKS_IDXS = OrderedDict() or the value of the 5-points

    • Adrian Rosebrock April 5, 2018 at 9:58 am #

      I’m not sure what you mean by the “value” in this context. The model is applied to the detected face and the returned “values” are the (x, y)-coordinates for each predicted facial landmark.

      • Girija April 9, 2018 at 3:12 am #

        I mean, I want to align face using this Dlib’s 5-point detector so how can i find the left eye center and right eye center, like you have done in 68 point using FACIAL_LANDMARKS_IDXS = OrderedDict()

      • Girija April 10, 2018 at 11:11 am #

        I mean, I want to align face using this Dlib’s 5-point landmark detector but i want to know that what i have to pass in place of “FACIAL_LANDMARKS_IDXS = OrderedDict([
        (“mouth”, (48, 68)),
        (“right_eyebrow”, (17, 22)),
        (“left_eyebrow”, (22, 27)),
        (“right_eye”, (36, 42)),
        (“left_eye”, (42, 48)),
        (“nose”, (27, 36)),
        (“jaw”, (0, 17))
        ])” (from 68 point facial landmark detection in helpers.py file ) to find the Center of right eye and left eye for facealignment using Dlib’s 5-point facial landmark detector.

        • Adrian Rosebrock April 10, 2018 at 11:51 am #

          You can compute the center of both eyes by computing the mid-point between the two respective coordinates for each eye. Keep in mind that with the 5-point model there are only two coordinates per eye.

          • Girija April 11, 2018 at 7:04 am #

            Thank you Adrian but i want to know that, how can i access those “two respective coordinates for each eye” from shape array to find the mid-points?

          • Adrian Rosebrock April 11, 2018 at 8:57 am #

            Take a look at the GIF at the top of this blog post (you can see the index of each facial landmark). Additionally, Lines 64-67 demonstrate how we loop over each of the facial landmarks and extract the (x, y)-coordinates. The right eye has indexes 0 and 1 while the left eye has indexes 3 and 4 (although the GIF is a mirror so they may be reversed; you’ll want to double-check for yourself).

  10. nidhi panda April 5, 2018 at 7:24 am #

    Hello Adrian, first of all thank you for the awesome blog post. Can you please tell this dlib’s new 5-point facial landmark detector is trained on with dataset as the 68 point model was trained for iBUG 300-W dataset.

    • Adrian Rosebrock April 5, 2018 at 9:57 am #

      The 5-point facial landmark model was trained on ~7,100 images that Davis King manually labeled. See this blog post for more details.

  11. nidhi panda April 5, 2018 at 12:27 pm #

    Thank you

  12. Den April 21, 2018 at 5:13 am #

    Hello Adrian!
    Thanks for interesting materials!

    Can you please help me?
    I want to control WS2812 addresable led, but “Make sure to run the script as root by using the sudo command. The rpi_ws281x library has to access the Pi hardware at a low level and requires running as root”.
    How I can control my leds from non-admin python script?


    • Adrian Rosebrock April 25, 2018 at 6:17 am #

      Which Python libraries are you using to control the LED? I assume GPIO?

  13. Amare April 25, 2018 at 1:41 am #

    Hi Adrian

    this dlib tracker seems good because i am not seeing it lost the face frequently. When i use kalman trackers it lost the object frequently (it track it , again lost it , again track it…….) s thank you for your time.
    Question: which tracker among others do you think that do not lost most frequently the object once it tracked (irrespective of occlusion)?

    • Adrian Rosebrock April 25, 2018 at 5:22 am #

      It’s hard to say because each tracker has their respective use cases. It’s highly dependent on your application and what you are trying to accomplish.

Leave a Reply