{
  "source_file": "0930",
  "source_platform": "技术平台",
  "author": "Satya Mallick / LearnOpenCV",
  "title_listed": "Face Detection with OpenCV DNN",
  "keywords": "人脸检测,OpenCV,DNN",
  "domain": "图像处理",
  "content_type": "教程",
  "is_paid_flag": "否",
  "url": "https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/",
  "publish_date": "2018-05",
  "corpus_stage": "预训练/SFT",
  "notes": "OpenCV人脸检测",
  "id": "739daab46816",
  "collected_at": "2026-10-02T17:29:29",
  "title": "Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )",
  "body_markdown": "We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience and analyze website traffic. By clicking “Accept,” you agree to our website's cookie use as described in our Cookie Policy. You can change your cookie settings at any time by clicking “Preferences.” \nAccept\n[ ![](../images/000.png) ](https://learnopencv.com)\n  * [Getting Started](https://learnopencv.com/category/install/)\n    * [Subscribe](https://learnopencv.com/)\n    * [Installation](https://learnopencv.com/category/install/)\n    * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n    * [PyTorch](https://learnopencv.com/getting-started-with-pytorch/)\n    * [Tensorflow & Keras](https://learnopencv.com/getting-started-with-tensorflow-keras/)\n  * [Free Courses](https://opencv.org/university/free-courses/?utm_source=lopcv&utm_medium=menu&utm_campaign=fcpage)\n    * [VLM Bootcamp](https://opencv.org/university/vision-language-model-bootcamp/?utm_source=lopcv&utm_medium=menu&utm_campaign=vlm)\n    * [PyTorch Bootcamp](https://opencv.org/university/free-pytorch-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=ptbc)\n    * [TensorFlow Keras Course](https://opencv.org/university/free-tensorflow-keras-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=tbc)\n    * [OpenCV Course](https://opencv.org/university/free-opencv-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=obc)\n    * [Python for Beginners](https://opencv.org/university/python-for-beginners/?utm_source=lopcv&utm_medium=menu&utm_campaign=pbc)\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=menu)\n  * [About](https://learnopencv.com/about/)\n\n\n  * [Getting Started](https://learnopencv.com/category/install/)\n    * [Subscribe](https://learnopencv.com/)\n    * [Installation](https://learnopencv.com/category/install/)\n    * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n    * [PyTorch](https://learnopencv.com/getting-started-with-pytorch/)\n    * [Tensorflow & Keras](https://learnopencv.com/getting-started-with-tensorflow-keras/)\n  * [Free Courses](https://opencv.org/university/free-courses/?utm_source=lopcv&utm_medium=menu&utm_campaign=fcpage)\n    * [VLM Bootcamp](https://opencv.org/university/vision-language-model-bootcamp/?utm_source=lopcv&utm_medium=menu&utm_campaign=vlm)\n    * [PyTorch Bootcamp](https://opencv.org/university/free-pytorch-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=ptbc)\n    * [TensorFlow Keras Course](https://opencv.org/university/free-tensorflow-keras-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=tbc)\n    * [OpenCV Course](https://opencv.org/university/free-opencv-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=obc)\n    * [Python for Beginners](https://opencv.org/university/python-for-beginners/?utm_source=lopcv&utm_medium=menu&utm_campaign=pbc)\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=menu)\n  * [About](https://learnopencv.com/about/)\n\n\nSearch ...\nResults\nSee all results\n  * [Home](https://learnopencv.com \"Home\")\n  * >\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/ \"Deep Learning\")\n  * >\n  * Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )\n\n\n[Vikas Gupta](https://learnopencv.com/author/vikas/)\n  * on  October 22, 2018\n\n\n# Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )\nUpdated July 31, 2026: The original tutorial, examples, media, narrative, and teaching order are preserved below. The labelled 2026 correction area adds only the verified API, compatibility, validation, and failure-handling changes needed for current OpenCV; where a historical snippet uses an obsolete API, the correction area is the runnable path.\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/), [DLIB](https://learnopencv.com/category/dlib/), [Face Application](https://learnopencv.com/category/face-application/), [Face Detection](https://learnopencv.com/category/face-detection/), [Machine Learning](https://learnopencv.com/category/machine-learning/), [Object Detection](https://learnopencv.com/category/object-detection/), [OpenCV](https://learnopencv.com/category/opencv/), [OpenCV DNN](https://learnopencv.com/category/opencv-dnn/)\n\n\n![Face Detection - Dlib, OpenCV, and Deep Learning \\( C++ / Python \\) featured image](../images/006.jpg)\n  *   *   * [ ](https://bigvision.ai/expert-ai-solution-builders?utm_source=lopcv&utm_medium=post-icon)\n\n\n**Updated July 31, 2026:** The original tutorial, examples, media, narrative, and teaching order are preserved below. The labelled 2026 correction area adds only the verified API, compatibility, validation, and failure-handling changes needed for current OpenCV; where a historical snippet uses an obsolete API, the correction area is the runnable path.\nIn this tutorial, we will discuss the various Face Detection methods in OpenCV, Dlib, and Deep Learning and compare the methods quantitatively. We will share code in C++ and Python for the following Face Detectors:\n  1. Haar Cascade Face Detector in OpenCV\n  2. Deep Learning based Face Detector in OpenCV.\n  3. HoG Face Detector in Dlib\n  4. Deep Learning based Dlib Face Detection\n\n\nWe will not go into the theory of any of them and only discuss their usage. We will also share some rules of thumb on which model to prefer according to your application.\nThroughout the post, we will assume image size of 300×300.\n## 1. Haar Cascade Face Detector in OpenCV\nHaar Cascade-based Face Detector was the state-of-the-art in Face Detection for many years since 2001 when Viola and Jones introduced it. There have been many improvements in recent years. OpenCV has many Haar-based models, which can be found **[in Github](https://github.com/opencv/opencv/tree/master/data/haarcascades)**.\n### Code\nPlease download the code from the link below. We have provided code snippets throughout the blog for better understanding. You will find CPP and python files for each face detector and a separate file that compares all the methods together ( run-all.py and run-all.cpp ). We also share all the models required for running the code.\n#### Python  \n|  1 2 3 4 5 6  |  `faceCascade ``=` `cv2.CascadeClassifier(``'./haarcascade_frontalface_default.xml'``)` `faces ``=` `faceCascade.detectMultiScale(frameGray)` `for` `face ``in` `faces:` `x1, y1, w, h ``=` `face` `x2 ``=` `x1 ``+` `w` `y2 ``=` `y1 ``+` `h`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12  |  `faceCascadePath = ``\"./haarcascade_frontalface_default.xml\"``;` `faceCascade.load( faceCascadePath )` `std::vector<Rect> faces;` `faceCascade.detectMultiScale(frameGray, faces);` `for` `( ``size_t` `i = 0; i < faces.size(); i++ )` `{` `int` `x1 = faces[i].x;` `int` `y1 = faces[i].y;` `int` `x2 = faces[i].x + faces[i].width;` `int` `y2 = faces[i].y + faces[i].height;` `}`  |  \n| --- | --- |  \nThe above code snippet loads the haar cascade model file and applies it to a grayscale image. the output is a list containing the detected faces. Each list member is again a list with 4 elements indicating the (x, y) coordinates of the top-left corner and the width and height of the detected face.\n### Pros\n  1. Works almost real-time on CPU\n  2. Simple Architecture\n  3. Detects faces at different scales\n\n\n### Cons\n  1. The major drawback of this method is that it gives many false predictions.\n  2. Doesn’t work on non-frontal images.\n  3. It doesn’t work under occlusion.\n\n\n## 2. DNN Face Detector in OpenCV\nThis model was included in OpenCV from version 3.3. It is based on a Single-Shot-Multibox detector and uses ResNet-10 Architecture as the backbone. The model was trained using images from the web, but the source is not disclosed. OpenCV provides 2 models for this face detector.\n  1. Floating point 16 version of the original caffe implementation ( 5.4 MB )\n  2. 8 bit quantized version using Tensorflow ( 2.7 MB )\n\n\nWe have included both models along with the code.\n### Code\n#### Python  \n|  1 2 3 4 5 6 7 8 9  |  `DNN ``=` `\"TF\"` `if` `DNN ``=``=` `\"CAFFE\"``:` `modelFile ``=` `\"res10_300x300_ssd_iter_140000_fp16.caffemodel\"` `configFile ``=` `\"deploy.prototxt\"` `net ``=` `cv2.dnn.readNetFromCaffe(configFile, modelFile)` `else``:` `modelFile ``=` `\"opencv_face_detector_uint8.pb\"` `configFile ``=` `\"opencv_face_detector.pbtxt\"` `net ``=` `cv2.dnn.readNetFromTensorflow(modelFile, configFile)`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11  |  `const` `std::string caffeConfigFile = ``\"./deploy.prototxt\"``;` `const` `std::string caffeWeightFile = ``\"./res10_300x300_ssd_iter_140000_fp16.caffemodel\"``;` `const` `std::string tensorflowConfigFile = ``\"./opencv_face_detector.pbtxt\"``;` `const` `std::string tensorflowWeightFile = ``\"./opencv_face_detector_uint8.pb\"``;` `#ifdef CAFFE` `Net net = cv::dnn::readNetFromCaffe(caffeConfigFile, caffeWeightFile);` `#else` `Net net = cv::dnn::readNetFromTensorflow(tensorflowWeightFile, tensorflowConfigFile);` `#endif`  |  \n| --- | --- |  \nWe load the required model using the above code. If we want to use the floating point model of Caffe, we use the caffemodel and prototxt files. Otherwise, we use the quantized TensorFlow model. Also, note the difference in how we read the networks for Caffe and Tensorflow.\n#### Python  \n|  1 2 3 4 5 6 7 8 9 10 11 12  |  `blob ``=` `cv2.dnn.blobFromImage(frameOpencvDnn, ``1.0``, (``300``, ``300``), [``104``, ``117``, ``123``], ``False``, ``False``)` `net.setInput(blob)` `detections ``=` `net.forward()` `bboxes ``=` `[]` `for` `i ``in` `range``(detections.shape[``2``]):` `confidence ``=` `detections[``0``, ``0``, i, ``2``]` `if` `confidence > conf_threshold:` `x1 ``=` `int``(detections[``0``, ``0``, i, ``3``] ``*` `frameWidth)` `y1 ``=` `int``(detections[``0``, ``0``, i, ``4``] ``*` `frameHeight)` `x2 ``=` `int``(detections[``0``, ``0``, i, ``5``] ``*` `frameWidth)` `y2 ``=` `int``(detections[``0``, ``0``, i, ``6``] ``*` `frameHeight)`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  |  `#ifdef CAFFE` `cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, ``false``, ``false``);` `#else` `cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, ``true``, ``false``);` `#endif` `net.setInput(inputBlob, ``\"data\"``);` `cv::Mat detection = net.forward(``\"detection_out\"``);` `cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<``float``>());` `for``(``int` `i = 0; i &lt; detectionMat.rows; i++)` `{` `float` `confidence = detectionMat.at&lt;``float``&gt;(i, 2);` `if``(confidence &gt; confidenceThreshold)` `{` `int` `x1 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 3) * frameWidth);` `int` `y1 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 4) * frameHeight);` `int` `x2 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 5) * frameWidth);` `int` `y2 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 6) * frameHeight);` `cv::rectangle(frameOpenCVDNN, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0),2, 4);` `}` `}`  |  \n| --- | --- |  \nIn the above code, the image is converted to a blob and passed through the network using the forward() function. The output detections is a 4-D matrix, where\n  * The 3rd dimension iterates over the detected faces. (i is the iterator over the number of faces)\n  * The fourth dimension contains information about the bounding box and the score for each face. For example, detections[0,0,0,2] gives the confidence score for the first face, and detections[0,0,0,3:6] give the bounding box.\n\n\nThe output coordinates of the bounding box are normalized between [0,1]. Thus the coordinates should be multiplied by the height and width of the original image to get the correct bounding box on the image.\n### Pros\nThe method has the following merits :\n  1. Most accurate out of the four methods\n  2. Runs at real-time on CPU\n  3. Works for different face orientations – up, down, left, right, side-face, etc.\n  4. Works even under substantial occlusion\n  5. Detects faces across various scales ( detects big as well as tiny faces )\n\n\nThe DNN-based detector overcomes all the drawbacks of the Haar cascade based detector without compromising on any benefit provided by Haar. We could not see any major drawback for this method except that it is slower than the Dlib HoG-based Face Detector discussed next.\nIt would be safe to say that it is time to bid farewell to Haar-based face detector and DNN based Face Detector should be the preferred choice in OpenCV.\n## 3. HoG Face Detector in Dlib\nThis is a widely used face detection model based on the [Histogram of Oriented Gradients](https://learnopencv.com/histogram-of-oriented-gradients/) (HoG) features and SVM. The model is built out of 5 HOG filters – front looking, left looking, right looking, front looking but rotated left, and a front looking but rotated right. The model comes embedded in the **[header file](https://github.com/davisking/dlib/blob/master/dlib/image_processing/frontal_face_detector.h)** itself.\nThe dataset used for training consists of 2825 images obtained from the LFW dataset and manually annotated by Davis King, the author of Dlib. It can be downloaded from **[here](http://dlib.net/files/data/dlib_face_detector_training_data.tar.gz)**.\n### Code\n#### Python  \n|  1 2 3 4 5 6 7  |  `hogFaceDetector ``=` `dlib.get_frontal_face_detector()` `faceRects ``=` `hogFaceDetector(frameDlibHogSmall, ``0``)` `for` `faceRect ``in` `faceRects:` `x1 ``=` `faceRect.left()` `y1 ``=` `faceRect.top()` `x2 ``=` `faceRect.right()` `y2 ``=` `faceRect.bottom()`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  |  `frontal_face_detector hogFaceDetector = get_frontal_face_detector();` `// Convert OpenCV image format to Dlib's image format` `cv_image<bgr_pixel> dlibIm(frameDlibHogSmall);` `// Detect faces in the image` `std::vector<dlib::rectangle> faceRects = hogFaceDetector(dlibIm);` `for` `( ``size_t` `i = 0; i < faceRects.size(); i++ )` `{` `int` `x1 = faceRects[i].left();` `int` `y1 = faceRects[i].top();` `int` `x2 = faceRects[i].right();` `int` `y2 = faceRects[i].bottom();` `cv::rectangle(frameDlibHog, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (``int``)(frameHeight/150.0), 4);` `}`  |  \n| --- | --- |  \nIn the above code, we first load the face detector. Then we pass it the image through the detector. The second argument is the number of times we want to upscale the image. The more you upscale, the better the chances of detecting smaller faces. However, upscaling the image will have a substantial impact on the computation speed. The output is in the form of a list of faces with the (x, y) coordinates of the diagonal corners.\n### Pros\n  1. Fastest method on CPU\n  2. Works very well for frontal and slightly non-frontal faces\n  3. Lightweight model as compared to the other three.\n  4. Works under small occlusion\n\n\nBasically, this method works under most cases except a few, as discussed below.\n### Cons\n  1. The major drawback is that it does not detect small faces, as it is trained for a minimum face size of 80×80. Thus, you need to ensure that the face size is more than that in your application. You can, however, train your own face detector for smaller-sized faces.\n  2. The bounding box often excludes part of the forehead and even part of the chin sometimes.\n  3. It does not work very well under substantial occlusion.\n  4. It does not work for side faces and extreme non-frontal faces, like looking down or up.\n\n\n## 4. Convolutional Neural Network – CNN Face Detector in Dlib\nThis method uses a **[Maximum-Margin Object Detector ( MMOD ) with CNN-based](https://arxiv.org/pdf/1502.00046.pdf)** features. The training process for this method is very simple and you don’t need a large amount of data to train a custom object detector. For more information on training, visit the **[dlib c++ library blog](http://blog.dlib.net/2016/10/easily-create-high-quality-object.html)**.\nThe model can be downloaded from the **[dlib-models repository](https://github.com/davisking/dlib-models)**.  \nIt uses a dataset manually labeled by its Author, Davis King, consisting of images from various datasets like ImageNet, PASCAL VOC, VGG, WIDER, Face Scrub. It contains 7220 images. The dataset can be downloaded from **[here.](http://dlib.net/files/data/dlib_face_detection_dataset-2016-09-30.tar.gz)**\n### Code\n#### Python  \n|  1 2 3 4 5 6 7  |  `dnnFaceDetector ``=` `dlib.cnn_face_detection_model_v1(``\"./mmod_human_face_detector.dat\"``)` `faceRects ``=` `dnnFaceDetector(frameDlibHogSmall, ``0``)` `for` `faceRect ``in` `faceRects:` `x1 ``=` `faceRect.rect.left()` `y1 ``=` `faceRect.rect.top()` `x2 ``=` `faceRect.rect.right()` `y2 ``=` `faceRect.rect.bottom()`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  |  `String mmodModelPath = ``\"./mmod_human_face_detector.dat\"``;` `net_type mmodFaceDetector;` `deserialize(mmodModelPath) >> mmodFaceDetector;` `// Convert OpenCV image format to Dlib's image format` `cv_image<bgr_pixel> dlibIm(frameDlibMmodSmall);` `matrix<rgb_pixel> dlibMatrix;` `assign_image(dlibMatrix, dlibIm);` `// Detect faces in the image` `std::vector<dlib::mmod_rect> faceRects = mmodFaceDetector(dlibMatrix);` `for` `( ``size_t` `i = 0; i < faceRects.size(); i++ )` `{` `int` `x1 = faceRects[i].rect.left();` `int` `y1 = faceRects[i].rect.top();` `int` `x2 = faceRects[i].rect.right();` `int` `y2 = faceRects[i].rect.bottom();` `cv::rectangle(frameDlibMmod, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (``int``)(frameHeight/150.0), 4);` `}`  |  \n| --- | --- |  \nThe code is similar to the HoG detector except that, in this case, we load the CNN face detection model. Also, the coordinates are present inside a rect object.\n### Pros\n  1. Works for different face orientations\n  2. Robust to occlusion\n  3. Works very fast on GPU\n  4. Very easy training process\n\n\n### Cons\n  1. Very slow on CPU\n  2. It does not detect small faces as it is trained for a minimum face size of 80×80. Thus, you need to ensure that the face size is more than that in your application. You can, however, train your own face detector for smaller-sized faces.\n  3. The bounding box is even smaller than the HoG detector.\n\n\n## 5. Accuracy Comparison\nI tried to evaluate the 4 models using the FDDB dataset using the [script used for evaluating the OpenCV-DNN model](https://github.com/opencv/opencv/blob/master/modules/dnn/misc/face_detector_accuracy.py). However, I found surprising results. Dlib had worse numbers than Haar, although visually dlib outputs look much better. Given below are the Precision scores for the 4 methods.\n[![face detectors in opencv and dlib - graph to help understand the wrong way of comparing dlib face detection with others methods](../images/008.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-coco-comparison.jpg)\n  \nWhere,  \nAP_50 = Precision when the overlap between Ground Truth and predicted bounding box is at least 50% ( IoU = 50% )  \nAP_75 = Precision when the overlap between Ground Truth and predicted bounding box is at least 75% ( IoU = 75% )  \nAP_Small = Average Precision for small size faces ( Average of IoU = 50% to 95% )  \nAP_medium = Average Precision for medium size faces ( Average of IoU = 50% to 95% )  \nAP_Large = Average Precision for large size faces ( Average of IoU = 50% to 95% )  \nmAP = Average precision across different IoU ( Average of IoU = 50% to 95% )\n**On closer inspection, I found that this evaluation is not fair for Dlib.**\n### 5.1. Evaluating accuracy the wrong way!\nAccording to my analysis, the reasons for lower numbers for dlib are as follows :\n[![comparing the face detected by OpenCV Haar with DNN, HoG and MOOD – single face tilted to left, occluded with hair](../images/010.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result1-e1539872861105.jpg)[![comparing the face detected by OpenCV Haar with DNN, HoG and MOOD – single face tilted to right, light shadow of hair](../images/011.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result2-e1539872827875.jpg)[![comparing the faces detected by OpenCV Haar with DNN, HoG and MOOD – multiple faces in image](../images/012.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095723/fd-acc-result3-e1539872783684.jpg)\n**Thus, the only relevant metric for a fair comparison between OpenCV and Dlib is AP_50 ( or even less than 50 since we mostly compare** the number of detected faces ). However, this point should always be considered while using the Dlib Face detectors.\n## 6. Speed Comparison\nWe used a 300×300 image for the comparison of the methods. The MMOD detector can be run on a GPU, but the support for NVIDIA GPUs in OpenCV is still not there. So, we evaluate the methods on CPU only and also report results for MMOD on GPU as well as CPU.\n#### Hardware used\nProcessor : Intel Core i7 6850K – 6 Core  \nRAM : 32 GB  \nGPU : NVIDIA GTX 1080 Ti with 11 GB RAM  \nOS : Linux 16.04 LTS  \nProgramming Language : Python\nWe run each method 10000 times on the given image and take 10 such iterations and average the time taken. Given below are the results.\n[![Bar graph showing the average time taken \\(speed\\) by different methods for tests run by us \\(dlib face detection\\)](../images/013.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095729/face-detection-speed-comparison.jpg)\nAs you can see from the image of this size, all the methods perform in real-time, except MMOD. MMOD detector is very fast on a GPU but is very slow on a CPU.\nIt should also be noted that these numbers can be different on different systems.\n## 7. Comparison under various conditions\nApart from accuracy and speed, there are some other factors that help us decide which one to use. In this section, we will compare the methods based on various other factors which are also important.\n### 7.1. Detection Across Scale\nWe will see an example where, in the same video, the person goes back n forth, thus making the face smaller and bigger. We notice that the OpenCV DNN (Deep Neural network) detects all the faces while Dlib detects only those faces which are bigger in size. We also show the size of the detected face along with the bounding box.\n[![GIF image comparing the accuracy of face detected in video by different methods – inference time is labeled for each method](../images/015.gif)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-scale-comparison.gif)\nIt can be seen that dlib based methods can detect faces of size up to ~(70×70) after which they fail to detect. As we discussed earlier, I think this is the major drawback of Dlib based methods. Since it is impossible to know the size of the face beforehand in most cases, we can get rid of this problem by upscaling the image, but then the speed advantage of dlib as compared to **OpenCV-DNN** goes away.\n### 7.2. Non-frontal Face\nNon-frontal can look towards the right, left, up, or down. Again, to be fair with dlib, we ensure the face size is more than 80×80. Given below are some examples.\n[![Comparing the face detection accuracy for non-frontal face, person looking down - inference time is labeled for each method](../images/016.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result7.jpg)[![Comparing the face detection accuracy for non-frontal face, person looking left - inference time is labeled for each method](../images/019.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result6.jpg)[![Comparing the face detection accuracy, non-frontal face when looking left down - inference time is labeled for each method](../images/022.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result5.jpg)[![Comparing the face detection accuracy, non-frontal face when looking right down - inference time is labeled for each method](../images/025.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result4.jpg)[![Comparing the face detection accuracy, non-frontal pose, 2 faces looking sideways - inference time is labeled for each method](../images/028.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result2.jpg)[![Comparing the face detection accuracy, non-frontal pose, 2 faces looking sideways - inference time is labeled for each method - cv2 cascade classifier](../images/031.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-non-frontal-result1.jpg)\nAs expected, **Haar** based detector fails totally. The hoG-based detector does detect faces for left or right looking faces ( since it was trained on them ) but is not as accurate as the**DNN-based** detectors of OpenCV and Dlib.\n### 7.3. Occlusion\nLet us see how well the methods perform under occlusion.\n[![Comparing the face detection accuracy, frontal pose, 2 faces, occlusion and only forehead - inference time is labeled for each method](../images/034.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/fd-occlusion-result1.jpg)[![Comparing the face detection accuracy, frontal pose, singe face partly out of frame 1 - inference time is labeled for each method](../images/036.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result2.jpg)[![Comparing the face detection accuracy, frontal pose, singe face partly out of frame 2 - inference time is labeled for each method - dlib face detection](../images/039.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result3.jpg)\nAgain, the DNN methods outperform the other two, with OpenCV-DNN slightly better than Dlib-MMOD. This is mainly because the CNN features are much more robust than HoG or Haar features.\n## 8. Conclusion\nWe discussed the pros and cons of each method in the respective sections. I recommend trying both OpenCV-DNN and HoG methods for your application and deciding accordingly. We share some tips to get started.\n#### General Case\nIn most applications, we won’t know the face size in the image beforehand. Thus, it is better to use OpenCV – DNN method as it is pretty fast and very accurate, even for small sized faces. It also detects faces at various angles. We recommend using OpenCV-DNN in most.\n#### For medium to large image sizes\nDlib HoG is the fastest method on the CPU. But it does not detect small sized faces ( < 70×70 ). So, if you know that your application will not be dealing with very small sized faces ( for example, a selfie app ), then HoG based Face detector is a better option. Also, If you can use a GPU, then the MMOD face detector is the best option as it is very fast on GPU and provides detection at various angles.\n#### High-resolution images\nSince feeding high-resolution images is not possible with these algorithms ( for computation speed ), HoG / MMOD detectors might fail when you scale down the image. On the other hand, the OpenCV-DNN method can be used for these since it detects small faces.\nHave any other suggestions? Please mention them in the comments, and we’ll update the post accordingly!\n## Must Read Articles  \n| We have crafted the following articles especially for you.  \n1. [What is Face Detection? – The Ultimate Guide](https://learnopencv.com/what-is-face-detection-the-ultimate-guide/)  \n2. [Anti-Spoofing Face Recognition System using OAK-D and DepthAI](https://learnopencv.com/anti-spoofing-face-recognition-system-using-oak-d-and-depthai/)  \n3. [Face Recognition with ArcFace](https://learnopencv.com/face-recognition-with-arcface/)  \n4. [Face Recognition: An Introduction for Beginners](https://learnopencv.com/face-recognition-an-introduction-for-beginners/ \"Face Recognition: An Introduction for Beginners\")  |  \n| --- |  \n## References\n[[FDDB Comparison code]](https://github.com/opencv/opencv/blob/master/modules/dnn/misc/face_detector_accuracy.py)  \n[[Dlib Blog]](http://blog.dlib.net/2016/10/easily-create-high-quality-object.html)  \n[[dlib mmod python example]](http://dlib.net/cnn_face_detector.py.html)  \n[[dlib mmod cpp example]](http://dlib.net/dnn_mmod_face_detection_ex.cpp.html)  \n[[OpenCV DNN Face detector]](https://github.com/opencv/opencv/tree/master/samples/dnn/face_detector)  \n[[Haar Based Face Detector]](https://docs.opencv.org/3.4/d7/d8b/tutorial_py_face_detection.html)\n## Verified 2026 Implementation and Corrections\n**Scope of this correction:** Add YuNet and label old benchmarks historical. The material below is retained from the tested modernization only where it addresses that scope; it does not replace the original explanation or examples above.\n## Choosing YuNet as the Primary Detector\nThe original 2018 comparison included OpenCV Haar, OpenCV Caffe/TensorFlow SSD, dlib HOG, and dlib MMOD. That snapshot is historically useful, but it is not the best default dependency graph for a current OpenCV project.\nThe refreshed implementation uses [YuNet](https://doi.org/10.1007/s11633-023-1423-y), a lightweight, anchor-free face detector designed for efficient inference. OpenCV exposes it through the high-level [`FaceDetectorYN`](https://docs.opencv.org/4.x/d0/dd4/tutorial_dnn_face.html) API, so the application does not need to reproduce model-specific preprocessing or non-maximum suppression.\nThe detector roles are now explicit:  \n| Detector  | Role in this tutorial  | Default dependency?  | Output  |  \n| --- | --- | --- | --- |  \n| YuNet through `FaceDetectorYN`  | Current primary path  | Yes  | Box, five landmarks, score  |  \n| OpenCV Haar cascade  | Optional historical baseline  | No  | Box  |  \n| dlib HOG  | Optional historical baseline  | No  | Box  |  \n| dlib MMOD  | Legacy material only  | No  | Not part of the current build or tests  |  \n| OpenCV Caffe/TensorFlow SSD  | Legacy assets only  | No  | Not loaded by current programs  |  \nThe filenames `face_detection_opencv_dnn.py` and `face_detection_opencv_dnn.cpp` remain for continuity with the original tutorial. Their current implementation loads YuNet ONNX through `FaceDetectorYN`; it does not load the retained Caffe or TensorFlow SSD files.\n### 2.1 Why the dynamic-input model matters\nThe current model is `face_detection_yunet_2026may.onnx`. Its height and width are dynamic, so the program can set the network input to each decoded frame’s actual size. The [pinned OpenCV Zoo model notes](https://github.com/opencv/opencv_zoo/blob/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/README.md) explain that this export replaces fixed height and width dimensions with symbolic dimensions for variable-resolution inference, including the OpenCV 5 ONNX Runtime path.\nDynamic input does not mean unlimited accuracy at every resolution. Very small, blurred, strongly occluded, or extreme-profile faces can still be missed. It means the model contract can accept changing frame dimensions without the application pretending every source is a fixed `300×300` image.\n## Setup and Verified Model Provenance\nUse Python 3.10 or newer with NumPy and OpenCV:  \n|  1 2  |  `python3 -m pip install -r requirements.txt` `python3 download_models.py`  |  \n| --- | --- |  \nThe primary requirements are intentionally small:  \n|  1 2  |  `numpy>=1.23,<3` `opencv-python>=4.10,<6`  |  \n| --- | --- |  \nThe model downloader pins one exact OpenCV Zoo state and verifies the bytes before installing the model:  \n| Field  | Verified value  |  \n| --- | --- |  \n| Model  | `face_detection_yunet_2026may.onnx`  |  \n| Upstream  | OpenCV Zoo  |  \n| Pinned commit  | `47534e27c9851bb1128ccc0102f1145e27f23f98`  |  \n| File size  |  `229,738` bytes  |  \n| SHA-256  | `ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0`  |  \n| License  | MIT  |  \n| Copyright  | Shiqi Yu  |  \nThe exact license is recorded in the companion project’s model provenance file and in the [pinned OpenCV Zoo license](https://github.com/opencv/opencv_zoo/blob/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/LICENSE). The downloader first writes to a temporary file, checks both size and SHA-256, and only then atomically moves the verified file into `models/`. An existing model is also reverified before reuse.\nThat workflow protects against a truncated transfer or an upstream file changing while a tutorial still claims reproducible results. It is an integrity check, not a malware scanner or a substitute for reviewing model provenance.\n## The FaceDetectorYN Pipeline\nThe core pipeline has four steps:\n  1. Create the detector once.\n  2. Set the detector input size to the current frame.\n  3. Run `detect`.\n  4. validate and draw the returned rows.\n\n\n### 4.1 Create the detector once\nThe Python wrapper checks the model path and the three main post-processing parameters before constructing OpenCV’s detector:  \n|  1 2 3 4 5 6 7 8 9 10 11  |  `backend_id, target_id ``=` `backend_target(device)` `self``._model ``=` `cv2.FaceDetectorYN.create(` `str``(model_path),` `\"\",` `(``320``, ``320``),` `score_threshold,` `nms_threshold,` `top_k,` `backend_id,` `target_id,` `)`  |  \n| --- | --- |  \nThe creation size is a valid initial size. The real input size is set immediately before each detection. The refreshed defaults are:\n  * `score_threshold=0.7`: discard lower-scoring candidates.\n  * `nms_threshold=0.3`: suppress sufficiently overlapping boxes after scoring.\n  * `top_k=5000`: cap the candidates retained before non-maximum suppression.\n  * `device=cpu`: pair OpenCV’s default DNN backend with the CPU target.\n\n\nLowering the score threshold can improve recall, but it usually increases false positives and the number of candidates processed by non-maximum suppression. Tune thresholds against labeled data from the actual camera and environment.\n### 4.2 Update the size and normalize empty results\nThe model returns one 15-value row per face. OpenCV uses `None` when Python has no detections, so the wrapper converts that case into an empty array with a stable shape:  \n|  1 2 3 4 5 6  |  `height, width ``=` `frame.shape[:``2``]` `self``._model.setInputSize((width, height))` `_, faces ``=` `self``._model.detect(frame)` `if` `faces ``is` `None``:` `return` `np.empty((``0``, ``15``), dtype``=``np.float32)` `return` `np.asarray(faces, dtype``=``np.float32).reshape(``-``1``, ``15``)`  |  \n| --- | --- |  \nNormalizing the empty case keeps downstream code simple: drawing, validation, and comparison can iterate over zero or more rows without a special `None` branch.\n### 4.3 Validate before drawing\nThe tutorial’s `--validate` mode checks invariants that should remain stable across codecs and supported OpenCV versions:\n  * the result is a two-dimensional array with 15 columns;\n  * every returned value is finite;\n  * box width and height are positive;\n  * the score is in `[0, 1]`;\n  * a clipped box has valid image bounds;\n  * saved images remain readable and preserve dimensions;\n  * saved videos reopen with the expected frame count and geometry.\n\n\nThe drawing function clips boxes before rendering, writes each score, and colors the five YuNet landmarks. Clipping is a visualization safeguard. It should not be used to hide invalid detector output, which is why validation also checks the original numeric values.\n## Run Face Detection on Images and Video\nThe program runs headlessly by default. It resolves its bundled model, sample video, and output folders relative to the script rather than the shell’s current directory.\n### 5.1 Video\nProcess two frames of the bundled video, save a `720×720` MJPEG AVI, and validate it:  \n|  1 2 3 4  |  `python3 face_detection_opencv_dnn.py \\` `--max-frames 2 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe output is `output/yunet-video.avi`. A limit of zero processes the full video. The writer uses the source width, height, and frame rate; when a source reports no usable frame rate, the example uses `25` FPS as a documented fallback.\nEvery decoded frame is processed exactly once. The writer is created from the source geometry before the loop, so the old pattern of consuming a first frame merely to discover its dimensions is avoided.\n### 5.2 Image\nFor an image, choose image mode explicitly and provide a path:  \n|  1 2 3 4 5 6  |  `python3 face_detection_opencv_dnn.py \\` `--input /absolute/path/to/face-image.jpg \\` `--mode image \\` `--output-dir /absolute/path/to/results \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe saved file is `yunet-image.jpg` and has the same width, height, and channel count as the decoded input. `--mode auto` uses common image suffixes and otherwise treats the input as video.\n### 5.3 Useful controls  \n| Option  | Purpose  |  \n| --- | --- |  \n| `--model PATH`  | Use a specific YuNet ONNX file  |  \n| `--device cpu|cuda`  | Choose the DNN backend/target pair  |  \n| `--score-threshold FLOAT`  | Filter low-confidence candidates  |  \n| `--nms-threshold FLOAT`  | Control overlap suppression  |  \n| `--top-k INTEGER`  | Limit candidates before NMS  |  \n| `--max-frames INTEGER`  | Bound video work for tests or previews  |  \n| `--display`  | Open an interactive window  |  \n| `--no-display`  | Make headless intent explicit  |  \n| `--validate`  | Check detections and saved output  |  \nCPU is the tested default. CUDA support depends on how OpenCV was built and was not part of this article’s regression matrix.\n## Compare YuNet, Haar, and dlib HOG\nThe comparison program defaults to YuNet alone, so it does not import dlib or require Haar. Optional detectors are created only when requested:  \n|  1 2 3 4 5  |  `python3 run-all.py \\` `--detectors yunet,haar \\` `--max-frames 1 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nEach detector receives the same original frame. Its annotated panel keeps the original `W×H` size, and the panels are concatenated horizontally. Two detectors therefore produce a `2W×H` frame. On the `720×720` fixture, the tested YuNet-plus-Haar comparison wrote `1440×720`, with two YuNet detections and one Haar detection.\nThat single frame is regression evidence, not an accuracy ranking. A meaningful detector comparison needs a labeled dataset, a fixed matching policy, precision-recall metrics, and representative pose, scale, lighting, and occlusion.\n### 6.1 Haar cascade\nHaar remains useful for teaching classical cascaded detection and for constrained frontal-face scenarios. The optional wrapper resizes to a fixed height, converts to grayscale, detects faces, and scales each box back independently in `x` and `y`.\nThe C++ Haar target is built only with OpenCV 4. In the tested OpenCV 5 configuration, the historical `CascadeClassifier` path is not available through the core API used by this project, so CMake disables that target. Python reports a clear error if its OpenCV binding lacks `CascadeClassifier`.\n### 6.2 dlib HOG\ndlib’s frontal detector is a HOG-pyramid detector with five embedded filters for frontal, side-looking, and rotated-frontal views, as documented in the [official dlib source](https://dlib.net/dlib/image_processing/frontal_face_detector.h.html). Install it only when you want this baseline:  \n|  1 2 3 4 5  |  `python3 -m pip install -r requirements-dlib.txt` `python3 face_detection_dlib_hog.py \\` `--max-frames 2 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe Python import is lazy, and the C++ targets are added only when CMake finds `dlib::dlib`. The current default path never unpacks the historical `dlib.zip`. dlib was not installed in the validation environment, so its actual detection output was not tested for this refresh; only the clear missing-dependency behavior and CMake’s clean disable path were checked.\n## Build and Run the C++ Program\nThe C++ project requires CMake 3.16 or newer, a C++17 compiler, and OpenCV 4.10 or newer but earlier than 6:  \n|  1 2 3  |  `cmake -S . -B build -DCMAKE_BUILD_TYPE=Release` `cmake --build build --parallel` `ctest --test-dir build --output-on-failure`  |  \n| --- | --- |  \nRun the primary video path:  \n|  1 2 3 4  |  `./build/face_detection_opencv_dnn \\` `--max-frames 2 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe C++ detector uses the same API and parameters as Python:  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13  |  `model_ = cv::FaceDetectorYN::create(` `model_path.string(),` `\"\"``,` `cv::Size(320, 320),` `score_threshold,` `nms_threshold,` `top_k,` `backend_id,` `target_id);` `model_->setInputSize(frame.size());` `cv::Mat faces;` `model_->detect(frame, faces);`  |  \n| --- | --- |  \nEach `CV_32F` row must have 15 columns. The wrapper copies the first four values into a rectangle, the next ten into five landmarks, and the final value into the score. Both language paths then share the same conceptual validation and output contract.\nAll default C++ targets compile with strict warnings treated as errors on Clang and GCC. Tests are registered only after the verified model exists, which turns a missing setup step into a clear configure-time error.\n## Tested Results\nThe refresh was tested from unrelated working directories so that accidental dependence on the caller’s current folder would fail.  \n| Path  | Environment  | Result  |  \n| --- | --- | --- |  \n| Python tests  | Python 3.14.3, OpenCV 4.13.0  |  `5/5` passed  |  \n| C++ tests  | OpenCV 4.12.0, C++17  |  `2/2` CTests passed  |  \n| Python tests  | Official OpenCV 5.0.0 build  |  `5/5` passed  |  \n| C++ tests  | Official OpenCV 5.0.0 build, C++17  |  `2/2` CTests passed  |  \nThe stable fixture results were:\n  * one `720×720` image: exactly two YuNet faces;\n  * two video frames: `720×720`, exactly two frames saved, four YuNet detections in total;\n  * YuNet-only comparison: `720×720`, two frames, four detections in total;\n  * YuNet plus Haar on one OpenCV 4 frame: `1440×720`, two YuNet detections and one Haar detection;\n  * a missing input returns exit code `2` with a specific read/open error;\n  * the model size and SHA-256 checks pass before inference.\n\n\nImage and video tests assert dimensions, frame counts, valid boxes, finite landmarks, confidence bounds, and readable output. They do not compare encoded JPEG or AVI bytes, because codec output can vary even when decoded geometry and detections are correct.\nExact OpenCV 4.14 was not available in the local validation environment. It remains the intended OpenCV 4 release target, but this handoff does not claim an exact 4.14 run. The OpenCV 5 build used for testing did not include ONNX Runtime, so OpenCV’s native DNN fallback was exercised rather than the OpenCV 5 ONNX Runtime engine.\n### From idea to working model to real-time deployment\nBig Vision takes computer vision projects through the full journey, not just the easy parts.\n![Satya Mallick](../images/body-fe65e1f717d94c873fd9.jpg)\n**Satya Mallick** Founder - Big Vision & LearnOpenCV\n[ Talk to our Team ](https://bigvision.ai/expert-ai-solution-builders/)\n## Limitations and Production Guidance\n### 9.1 Measure on your data\nThe two-face fixture proves a stable execution path, not broad accuracy. Build a labeled validation set that includes the smallest expected face, motion blur, masks, glasses, partial occlusion, profile views, backlighting, skin-tone diversity, camera compression, and realistic non-face negatives. Measure precision and recall over threshold choices instead of choosing `0.7` from one screenshot.\n### 9.2 Detection is frame-local\nThe example detects every frame independently. It does not attach persistent identities, smooth boxes, or bridge missed detections. For video analytics, add a tracker and define when a track is created, confirmed, lost, and retired.\n### 9.3 Landmarks are sparse\nYuNet’s five points can support coarse alignment. Applications that need eye contours, expression geometry, dense face meshes, or robust pose estimation should use a dedicated landmark model after detection.\n### 9.4 Backend support is build-specific\n`--device cuda` works only when the installed OpenCV DNN build supports the requested CUDA backend and target. OpenCV 5 can also use an ONNX Runtime engine for the dynamic model, but that exact engine was not present in this test build. Benchmark the precise OpenCV package, backend, target, model, resolution, and hardware that will ship.\n### 9.5 Treat privacy and misuse as engineering requirements\nFaces are personal data in many contexts. Minimize collection, document retention, protect stored media, and obtain appropriate consent. A detector’s confidence score is not proof of identity, age, emotion, intent, or liveness.\nWas This Article Helpful?\nPost Views: 123\n## Subscribe & Download Code\nIf you liked this article and would like to download code (C++ and Python) and example images used in this post, please [click here](javascript:void\\(0\\)). In our newsletter, we share Computer Vision and AI tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.  \n  \n\n[ Download Example Code](javascript:void\\(0\\))\n  \n  \n\n[PrevPreviousKatharsis : A Software Engineer’s first steps in Computer Vision and Machine Learning](https://learnopencv.com/katharsis-software-engineers-first-step-in-cvml/)\n[NextInstall OpenCV from source on Windows – C++ / PythonNext](https://learnopencv.com/install-opencv-4-on-windows/)\n###  [ Train RF-DETR for Instance Segmentation with GPT-6 Astra ](https://learnopencv.com/astra-rf-detr-microduck-segmentation/)\nBefore a flight, I left Astra a short prompt and a signed-in Roboflow account. It\n###  [ How 10x AI Engineers Train Models for Production: Lessons from PINTO’s Face Alignment Project ](https://learnopencv.com/how-10x-ai-engineers-train-models-for-production/)\nLearn a production model training playbook from PINTO’s face alignment project: reframe the task, engineer\n###  [ VGGT vs. VGGT-Ω (VGGT-Omega): A Complete Guide to Feed-Forward 3D Reconstruction ](https://learnopencv.com/vggt-vs-vggt-%cf%89-vggt-omega-a-complete-guide-to-feed-forward-3d-reconstruction/)\nHow VGGT and VGGT-Ω work, what changed, and real benchmark numbers, speed, GPU memory, depth,\n![Satya Mallick](../images/body-fe65e1f717d94c873fd9.jpg)\n#### Satya Mallick, Ph.D.\nFounder - Big Vision & LearnOpenCV\n#####  Are you struggling with your Computer Vision Product Development?\nHelping startups and enterprises build and deploy scalable solutions that work in the real world.\n[ Schedule a Call ](https://bigvision.ai/expert-ai-solution-builders?utm_source=lopcv&utm_medium=post)\n####  Table of Contents\n  1. [1. Haar Cascade Face Detector in OpenCV](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-0)\n  2. [2. DNN Face Detector in OpenCV](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-1)\n  3. [3. HoG Face Detector in Dlib](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-2)\n  4. [4. Convolutional Neural Network – CNN Face Detector in Dlib](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-3)\n  5. [5. Accuracy Comparison](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-4)\n  6. [6. Speed Comparison](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-5)\n  7. [7. Comparison under various conditions](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-6)\n  8. [8. Conclusion](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-7)\n  9. [Must Read Articles](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-8)\n  10. [References](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-9)\n  11. [Verified 2026 Implementation and Corrections](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#verified-2026-implementation-and-corrections)\n  12. [Choosing YuNet as the Primary Detector](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-2-choosing-yunet-as-the-primary-detector)\n  13. [Setup and Verified Model Provenance](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-3-setup-and-verified-model-provenance)\n  14. [The FaceDetectorYN Pipeline](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-4-the-facedetectoryn-pipeline)\n  15. [Run Face Detection on Images and Video](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-5-run-face-detection-on-images-and-video)\n  16. [Compare YuNet, Haar, and dlib HOG](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-6-compare-yunet-haar-and-dlib-hog)\n  17. [Build and Run the C++ Program](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-7-build-and-run-the-c-program)\n  18. [Tested Results](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-8-tested-results)\n  19. [Limitations and Production Guidance](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-9-limitations-and-production-guidance)\n\n\nWas This Article Helpful?\n  * [C++](https://learnopencv.com/tag/c/), [cascadeClassifier](https://learnopencv.com/tag/cascade-classifier/), [Comparison](https://learnopencv.com/tag/comparison/), [cv2.CascadeClassifier](https://learnopencv.com/tag/cv2-cascadeclassifier/), [cv2.dnn](https://learnopencv.com/tag/cv2-dnn/), [cv2.dnn.blobFromImage](https://learnopencv.com/tag/cv2-dnn-blobfromimage/), [cv2.dnn.readNetFromCaffe](https://learnopencv.com/tag/cv2-dnn-readnetfromcaffe/), [cv2.dnn.readNetFromTensorflow](https://learnopencv.com/tag/cv2-dnn-readnetfromtensorflow/), [dlib.cnn_face_detection_model_v1](https://learnopencv.com/tag/dlib-cnn_face_detection_model_v1/), [dlib.get_frontal_face_detector](https://learnopencv.com/tag/dlib-get_frontal_face_detector/), [dnnFaceDetector](https://learnopencv.com/tag/dnnfacedetector/), [evaluation](https://learnopencv.com/tag/evaluation/), [faceDetector](https://learnopencv.com/tag/facedetector/), [haarCascade](https://learnopencv.com/tag/haarcascade/), [HOG](https://learnopencv.com/tag/hog/), [hogFaceDetector](https://learnopencv.com/tag/hogfacedetector/), [mmodFaceDetector](https://learnopencv.com/tag/mmodfacedetector/), [performanceComparision](https://learnopencv.com/tag/performancecomparision/), [Python](https://learnopencv.com/tag/python/), [readNetFromCaffe](https://learnopencv.com/tag/readnetfromcaffe/), [readNetFromTensorflow](https://learnopencv.com/tag/readnetfromtensorflow/), [tensorflow](https://learnopencv.com/tag/tensorflow/)\n\n\n## Read Next\n[ ![Decoding Virat Kohli’s Flick Shot: AI-Based 3D Motion Reconstruction](../images/body-f3950ee9e907f51f83d3.png) ](https://learnopencv.com/decoding-virat-kohlis-flick-shot-ai-based-3d-motion-reconstruction/)\n[3D Computer Vision](https://learnopencv.com/category/3d-computer-vision/)[3D Reconstruction](https://learnopencv.com/category/3d-computer-vision/3d-reconstruction/)[Segmentation](https://learnopencv.com/category/segmentation/)[SpatialAI-Depth](https://learnopencv.com/category/3d-computer-vision/spatialai-depth/)[Video Analysis](https://learnopencv.com/category/video-analysis/)\n[Adnan Shaikh](https://learnopencv.com/author/adnan/) July 18, 2026 \n##  [ Decoding Virat Kohli’s Flick Shot: AI-Based 3D Motion Reconstruction ](https://learnopencv.com/decoding-virat-kohlis-flick-shot-ai-based-3d-motion-reconstruction/)\nReconstruct the 3D swing plane of Virat Kohli's flick shot from a single 2D video with off-the-shelf vision models. No…\n[ ![How to Run Object Detection with OpenCV 5](../images/body-6f304990249f37d13c7f.jpg) ](https://learnopencv.com/how-to-run-object-detection-with-opencv-5/)\n[Object Detection](https://learnopencv.com/category/object-detection/)[OpenCV 5](https://learnopencv.com/category/opencv/opencv-5/)[OpenCV DNN](https://learnopencv.com/category/opencv-dnn/)[YOLO](https://learnopencv.com/category/yolo/)\n[Sudip Chakrabarty](https://learnopencv.com/author/sudip/) July 9, 2026 \n##  [ How to Run Object Detection with OpenCV 5 ](https://learnopencv.com/how-to-run-object-detection-with-opencv-5/)\nLearn about the new OpenCV 5 and how to use its DNN engine to run object detection models on the…\n[ ![How to Fine-Tune YOLO26 for Safety Gear and Sign Language Detection](../images/body-6b014d4d46a21419f999.jpg) ](https://learnopencv.com/how-to-fine-tune-yolo26-for-safety-gear-and-sign-language-detection/)\n[Computer Vision](https://learnopencv.com/category/computer-vision/)[Object Detection](https://learnopencv.com/category/object-detection/)[YOLO](https://learnopencv.com/category/yolo/)\n[Sudip Chakrabarty](https://learnopencv.com/author/sudip/) June 18, 2026 \n##  [ How to Fine-Tune YOLO26 for Safety Gear and Sign Language Detection ](https://learnopencv.com/how-to-fine-tune-yolo26-for-safety-gear-and-sign-language-detection/)\nLearn how to fine-tune YOLO26 on your own data. We build a construction PPE safety detector and a sign-language reader…\n##  Subscribe to our Newsletter\nSubscribe to our email newsletter to get the latest posts delivered right to your email.\nName \nEmail \nSend\n![](../images/body-2dd5ce664c5fca7d56f8.png)\nEmpowering innovation through education, LearnOpenCV provides in-depth tutorials, code, and guides in AI, Computer Vision, and Deep Learning. Led by Dr. Satya Mallick, we're dedicated to nurturing a community keen on technology breakthroughs.\n[ Read More ](https://learnopencv.com/about/)\nCategories\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/)\n  * [Object Detection](https://learnopencv.com/category/object-detection/)\n  * [Image Classification](https://learnopencv.com/category/image-classification)\n  * [YOLO](https://learnopencv.com/category/yolo/)\n  * [Image Processing](https://learnopencv.com/category/image-processing/)\n  * [Image Segmentation](https://learnopencv.com/category/image-segmentation/)\n\n\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/)\n  * [Object Detection](https://learnopencv.com/category/object-detection/)\n  * [Image Classification](https://learnopencv.com/category/image-classification)\n  * [YOLO](https://learnopencv.com/category/yolo/)\n  * [Image Processing](https://learnopencv.com/category/image-processing/)\n  * [Image Segmentation](https://learnopencv.com/category/image-segmentation/)\n\n\nGetting Started\n  * [Installation](https://learnopencv.com/category/install/)\n  * [PyTorch](https://learnopencv.com/learn-pytorch/)\n  * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n  * [Keras & Tensorflow](https://learnopencv.com/learn-keras-and-tensorflow/)\n\n\n  * [Installation](https://learnopencv.com/category/install/)\n  * [PyTorch](https://learnopencv.com/learn-pytorch/)\n  * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n  * [Keras & Tensorflow](https://learnopencv.com/learn-keras-and-tensorflow/)\n\n\nBig Vision\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=footer)\n  * [Case Studies](https://bigvision.ai/case-studies/?utm_source=locv&utm_medium=footer)\n  * [Get in Touch](https://bigvision.ai/contact-us/?utm_source=locv&utm_medium=footer)\n\n\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=footer)\n  * [Case Studies](https://bigvision.ai/case-studies/?utm_source=locv&utm_medium=footer)\n  * [Get in Touch](https://bigvision.ai/contact-us/?utm_source=locv&utm_medium=footer)\n\n\nCopyright © 2026 – BIG VISION LLC [Privacy Policy](https://learnopencv.com/privacy-policy/) [Terms and Conditions](https://learnopencv.com/terms-and-conditions/)\n  * [ ](https://bit.ly/Facebook_LearnOpenCV)\n  * [ ](https://www.instagram.com/learnopencv/)\n  * [ ](https://www.linkedin.com/in/satyamallick/)\n  * [ ](https://x.com/LearnOpenCV)\n  * [ ](https://www.youtube.com/c/LearnOpenCV?utm_source=lopcv&utm_medium=footer&utm_campaign=yt)\n\n\n[ ![](../images/body-ab5d272e3cb213d5eb46.png) Click here to download the source code to this post ](javascript:void\\(0\\))\n",
  "metadata": {
    "title": "Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )",
    "description": "Empirical comparison of Face Detectors in OpenCV, Dlib face detection & Deep Learning. Face Detectors based on Haar Cascade, HoG, and Deep Learning in Dlib.",
    "keywords": "dnnfacedetector,mmodfacedetector,dlib.cnn_face_detection_model_v1,cv2.dnn.blobfromimage,hogfacedetector,dlib.get_frontal_face_detector,performancecomparision,hog,c++,python,tensorflow,facedetector,evaluation,comparison,cv2.cascadeclassifier,cv2.dnn.readnetfromcaffe,readnetfromcaffe,cv2.dnn.readnetfromtensorflow,readnetfromtensorflow,haar cascade,cv2.dnn,cascadeclassifier,what is dlib used for?,is dlib necessary for face recognition?,how do i install dlib for face recognition?,haarcascade",
    "author": "Vikas Gupta",
    "og:locale": "en_US",
    "og:site_name": "LearnOpenCV – Learn OpenCV, PyTorch, Keras, Tensorflow with code, & tutorials",
    "og:type": "article",
    "og:title": "Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )",
    "og:description": "Empirical comparison of Face Detectors in OpenCV, Dlib face detection & Deep Learning. Face Detectors based on Haar Cascade, HoG, and Deep Learning in Dlib.",
    "og:url": "https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/",
    "og:image": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/31023437/face-detection-opencv-dlib-and-deep-learning-c-python-featured-2026.jpg",
    "og:image:secure_url": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/31023437/face-detection-opencv-dlib-and-deep-learning-c-python-featured-2026.jpg",
    "og:image:width": "1600",
    "og:image:height": "900",
    "twitter:card": "summary",
    "twitter:site": "@AiOpencv",
    "twitter:title": "Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )",
    "twitter:description": "Empirical comparison of Face Detectors in OpenCV, Dlib face detection & Deep Learning. Face Detectors based on Haar Cascade, HoG, and Deep Learning in Dlib.",
    "twitter:creator": "@AiOpencv",
    "twitter:image": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/31023437/face-detection-opencv-dlib-and-deep-learning-c-python-featured-2026.jpg",
    "article:published_time": "2018-10-22T12:25:47+00:00",
    "article:modified_time": "2026-07-31T09:34:42+00:00",
    "article:publisher": "https://www.facebook.com/Learnopencv-277284889389059"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [],
  "images": [
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2024/02/04103923/learnOpenCV_by_bigvision1.png",
      "bytes": 6527,
      "reused": true,
      "local_path": "attachments/739daab46816/images/000.png",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2024/02/04103923/learnOpenCV_by_bigvision1.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/31023437/face-detection-opencv-dlib-and-deep-learning-c-python-featured-2026.jpg",
      "bytes": 383360,
      "reused": true,
      "local_path": "attachments/739daab46816/images/006.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/31023437/face-detection-opencv-dlib-and-deep-learning-c-python-featured-2026.jpg",
      "alt": "Face Detection - Dlib, OpenCV, and Deep Learning \\( C++ / Python \\) featured image",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-coco-comparison.jpg",
      "bytes": 19621,
      "reused": true,
      "local_path": "attachments/739daab46816/images/008.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-coco-comparison.jpg",
      "alt": "face detectors in opencv and dlib - graph to help understand the wrong way of comparing dlib face detection with others methods",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result1-e1539872861105.jpg",
      "bytes": 37322,
      "reused": true,
      "local_path": "attachments/739daab46816/images/010.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result1-e1539872861105.jpg",
      "alt": "comparing the face detected by OpenCV Haar with DNN, HoG and MOOD – single face tilted to left, occluded with hair",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result2-e1539872827875.jpg",
      "bytes": 46888,
      "reused": true,
      "local_path": "attachments/739daab46816/images/011.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result2-e1539872827875.jpg",
      "alt": "comparing the face detected by OpenCV Haar with DNN, HoG and MOOD – single face tilted to right, light shadow of hair",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095723/fd-acc-result3-e1539872783684.jpg",
      "bytes": 58030,
      "reused": true,
      "local_path": "attachments/739daab46816/images/012.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095723/fd-acc-result3-e1539872783684.jpg",
      "alt": "comparing the faces detected by OpenCV Haar with DNN, HoG and MOOD – multiple faces in image",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095729/face-detection-speed-comparison.jpg",
      "bytes": 17147,
      "reused": true,
      "local_path": "attachments/739daab46816/images/013.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095729/face-detection-speed-comparison.jpg",
      "alt": "Bar graph showing the average time taken \\(speed\\) by different methods for tests run by us \\(dlib face detection\\)",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-scale-comparison.gif",
      "bytes": 1563498,
      "reused": true,
      "local_path": "attachments/739daab46816/images/015.gif",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-scale-comparison.gif",
      "alt": "GIF image comparing the accuracy of face detected in video by different methods – inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result7.jpg",
      "bytes": 25355,
      "reused": true,
      "local_path": "attachments/739daab46816/images/016.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result7.jpg",
      "alt": "Comparing the face detection accuracy for non-frontal face, person looking down - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result6.jpg",
      "bytes": 30473,
      "reused": true,
      "local_path": "attachments/739daab46816/images/019.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result6.jpg",
      "alt": "Comparing the face detection accuracy for non-frontal face, person looking left - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result5.jpg",
      "bytes": 28435,
      "reused": true,
      "local_path": "attachments/739daab46816/images/022.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result5.jpg",
      "alt": "Comparing the face detection accuracy, non-frontal face when looking left down - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result4.jpg",
      "bytes": 27855,
      "reused": true,
      "local_path": "attachments/739daab46816/images/025.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result4.jpg",
      "alt": "Comparing the face detection accuracy, non-frontal face when looking right down - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result2.jpg",
      "bytes": 34591,
      "reused": true,
      "local_path": "attachments/739daab46816/images/028.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result2.jpg",
      "alt": "Comparing the face detection accuracy, non-frontal pose, 2 faces looking sideways - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-non-frontal-result1.jpg",
      "bytes": 34808,
      "reused": true,
      "local_path": "attachments/739daab46816/images/031.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-non-frontal-result1.jpg",
      "alt": "Comparing the face detection accuracy, non-frontal pose, 2 faces looking sideways - inference time is labeled for each method - cv2 cascade classifier",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/fd-occlusion-result1.jpg",
      "bytes": 21267,
      "reused": true,
      "local_path": "attachments/739daab46816/images/034.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/fd-occlusion-result1.jpg",
      "alt": "Comparing the face detection accuracy, frontal pose, 2 faces, occlusion and only forehead - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result2.jpg",
      "bytes": 22736,
      "reused": true,
      "local_path": "attachments/739daab46816/images/036.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result2.jpg",
      "alt": "Comparing the face detection accuracy, frontal pose, singe face partly out of frame 1 - inference time is labeled for each method",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result3.jpg",
      "bytes": 21219,
      "reused": true,
      "local_path": "attachments/739daab46816/images/039.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result3.jpg",
      "alt": "Comparing the face detection accuracy, frontal pose, singe face partly out of frame 2 - inference time is labeled for each method - dlib face detection",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://opencv.org/university/wp-content/uploads/sites/4/2023/04/Dr-Satya.jpg",
      "bytes": 17778,
      "reused": false,
      "content_type": "image/jpeg",
      "local_path": "attachments/739daab46816/images/body-fe65e1f717d94c873fd9.jpg",
      "src": "https://opencv.org/university/wp-content/uploads/sites/4/2023/04/Dr-Satya.jpg",
      "alt": "Satya Mallick",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/16015539/decoding-virat-kohli-flick-shot-3d-motion-reconstruction.png",
      "bytes": 1911733,
      "reused": false,
      "content_type": "image/png",
      "local_path": "attachments/739daab46816/images/body-f3950ee9e907f51f83d3.png",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/16015539/decoding-virat-kohli-flick-shot-3d-motion-reconstruction.png",
      "alt": "Decoding Virat Kohli’s Flick Shot: AI-Based 3D Motion Reconstruction",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/11002616/OpenCV_5_Blog_Thumbnail_final-scaled.jpg",
      "bytes": 516266,
      "reused": false,
      "content_type": "image/jpeg",
      "local_path": "attachments/739daab46816/images/body-6f304990249f37d13c7f.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2026/07/11002616/OpenCV_5_Blog_Thumbnail_final-scaled.jpg",
      "alt": "How to Run Object Detection with OpenCV 5",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2026/06/17235330/YOLO26_Finetuning_Thumbnail_image-768x512.jpg",
      "bytes": 85542,
      "reused": false,
      "content_type": "image/jpeg",
      "local_path": "attachments/739daab46816/images/body-6b014d4d46a21419f999.jpg",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2026/06/17235330/YOLO26_Finetuning_Thumbnail_image-768x512.jpg",
      "alt": "How to Fine-Tune YOLO26 for Safety Gear and Sign Language Detection",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://cdn.learnopencv.com/wp-content/uploads/2025/12/04080755/learnOpenCV_by_bigvision1.png",
      "bytes": 6316,
      "reused": false,
      "content_type": "image/png",
      "local_path": "attachments/739daab46816/images/body-2dd5ce664c5fca7d56f8.png",
      "src": "https://cdn.learnopencv.com/wp-content/uploads/2025/12/04080755/learnOpenCV_by_bigvision1.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    },
    {
      "status": "ok",
      "url": "https://learnopencv.com/wp-content/uploads/2021/10/cropped-favicon-512x512-1.png",
      "bytes": 22729,
      "reused": false,
      "content_type": "image/png",
      "local_path": "attachments/739daab46816/images/body-ab5d272e3cb213d5eb46.png",
      "src": "https://learnopencv.com/wp-content/uploads/2021/10/cropped-favicon-512x512-1.png",
      "alt": "",
      "downloaded": true,
      "discovery": "saved_markdown"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/LearnOpenCV?utm_source=lopcv&utm_medium=footer&utm_campaign=yt",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://learnopencv.com"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/install/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/getting-started-with-opencv/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/getting-started-with-pytorch/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/getting-started-with-tensorflow-keras/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/about/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/author/vikas/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/dlib/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/face-application/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/face-detection/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/object-detection/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/opencv/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/category/opencv-dnn/"
    },
    {
      "type": "internal",
      "href": "https://learnopencv.com/histogram-of-oriented-gradients/"
    },
    {
      "type": "internal",
      "href": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-coco-comparison.jpg"
    },
    {
      "type": "internal",
      "href": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result1-e1539872861105.jpg"
    },
    {
      "type": "internal",
      "href": "https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result2-e1539872827875.jpg"
    },
    {
      "type": "external",
      "href": "https://opencv.org/university/free-courses/"
    },
    {
      "type": "external",
      "href": "https://opencv.org/university/vision-language-model-bootcamp/"
    },
    {
      "type": "external",
      "href": "https://opencv.org/university/free-pytorch-course/"
    },
    {
      "type": "external",
      "href": "https://opencv.org/university/free-tensorflow-keras-course/"
    },
    {
      "type": "external",
      "href": "https://opencv.org/university/free-opencv-course/"
    },
    {
      "type": "external",
      "href": "https://opencv.org/university/python-for-beginners/"
    },
    {
      "type": "external",
      "href": "https://bigvision.ai/expert-ai-solution-builders/"
    },
    {
      "type": "external",
      "href": "https://bigvision.ai/expert-ai-solution-builders"
    },
    {
      "type": "external",
      "href": "https://github.com/opencv/opencv/tree/master/data/haarcascades"
    },
    {
      "type": "external",
      "href": "https://github.com/davisking/dlib/blob/master/dlib/image_processing/frontal_face_detector.h"
    },
    {
      "type": "external",
      "href": "http://dlib.net/files/data/dlib_face_detector_training_data.tar.gz"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/pdf/1502.00046.pdf"
    },
    {
      "type": "external",
      "href": "http://blog.dlib.net/2016/10/easily-create-high-quality-object.html"
    },
    {
      "type": "external",
      "href": "https://github.com/davisking/dlib-models"
    },
    {
      "type": "external",
      "href": "http://dlib.net/files/data/dlib_face_detection_dataset-2016-09-30.tar.gz"
    },
    {
      "type": "external",
      "href": "https://github.com/opencv/opencv/blob/master/modules/dnn/misc/face_detector_accuracy.py"
    },
    {
      "type": "external",
      "href": "http://dlib.net/cnn_face_detector.py.html"
    },
    {
      "type": "external",
      "href": "http://dlib.net/dnn_mmod_face_detection_ex.cpp.html"
    },
    {
      "type": "external",
      "href": "https://github.com/opencv/opencv/tree/master/samples/dnn/face_detector"
    },
    {
      "type": "external",
      "href": "https://docs.opencv.org/3.4/d7/d8b/tutorial_py_face_detection.html"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:26:12Z",
  "source_url": "https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "http_403",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 23,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience and analyze website traffic. By clicking “Accept,” you agree to our website's cookie use as described in our Cookie Policy. You can change your cookie settings at any time by clicking “Preferences.” \nAccept\n[ ![](https://cdn.learnopencv.com/wp-content/uploads/2024/02/04103923/learnOpenCV_by_bigvision1.png) ](https://learnopencv.com)\n  * [Getting Started](https://learnopencv.com/category/install/)\n    * [Subscribe](https://learnopencv.com/)\n    * [Installation](https://learnopencv.com/category/install/)\n    * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n    * [PyTorch](https://learnopencv.com/getting-started-with-pytorch/)\n    * [Tensorflow & Keras](https://learnopencv.com/getting-started-with-tensorflow-keras/)\n  * [Free Courses](https://opencv.org/university/free-courses/?utm_source=lopcv&utm_medium=menu&utm_campaign=fcpage)\n    * [VLM Bootcamp](https://opencv.org/university/vision-language-model-bootcamp/?utm_source=lopcv&utm_medium=menu&utm_campaign=vlm)\n    * [PyTorch Bootcamp](https://opencv.org/university/free-pytorch-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=ptbc)\n    * [TensorFlow Keras Course](https://opencv.org/university/free-tensorflow-keras-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=tbc)\n    * [OpenCV Course](https://opencv.org/university/free-opencv-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=obc)\n    * [Python for Beginners](https://opencv.org/university/python-for-beginners/?utm_source=lopcv&utm_medium=menu&utm_campaign=pbc)\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=menu)\n  * [About](https://learnopencv.com/about/)\n\n\n  * [Getting Started](https://learnopencv.com/category/install/)\n    * [Subscribe](https://learnopencv.com/)\n    * [Installation](https://learnopencv.com/category/install/)\n    * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n    * [PyTorch](https://learnopencv.com/getting-started-with-pytorch/)\n    * [Tensorflow & Keras](https://learnopencv.com/getting-started-with-tensorflow-keras/)\n  * [Free Courses](https://opencv.org/university/free-courses/?utm_source=lopcv&utm_medium=menu&utm_campaign=fcpage)\n    * [VLM Bootcamp](https://opencv.org/university/vision-language-model-bootcamp/?utm_source=lopcv&utm_medium=menu&utm_campaign=vlm)\n    * [PyTorch Bootcamp](https://opencv.org/university/free-pytorch-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=ptbc)\n    * [TensorFlow Keras Course](https://opencv.org/university/free-tensorflow-keras-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=tbc)\n    * [OpenCV Course](https://opencv.org/university/free-opencv-course/?utm_source=lopcv&utm_medium=menu&utm_campaign=obc)\n    * [Python for Beginners](https://opencv.org/university/python-for-beginners/?utm_source=lopcv&utm_medium=menu&utm_campaign=pbc)\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=menu)\n  * [About](https://learnopencv.com/about/)\n\n\nSearch ...\nResults\nSee all results\n  * [Home](https://learnopencv.com \"Home\")\n  * >\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/ \"Deep Learning\")\n  * >\n  * Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )\n\n\n[Vikas Gupta](https://learnopencv.com/author/vikas/)\n  * on  October 22, 2018\n\n\n# Face Detection – Dlib, OpenCV, and Deep Learning ( C++ / Python )\nUpdated July 31, 2026: The original tutorial, examples, media, narrative, and teaching order are preserved below. The labelled 2026 correction area adds only the verified API, compatibility, validation, and failure-handling changes needed for current OpenCV; where a historical snippet uses an obsolete API, the correction area is the runnable path.\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/), [DLIB](https://learnopencv.com/category/dlib/), [Face Application](https://learnopencv.com/category/face-application/), [Face Detection](https://learnopencv.com/category/face-detection/), [Machine Learning](https://learnopencv.com/category/machine-learning/), [Object Detection](https://learnopencv.com/category/object-detection/), [OpenCV](https://learnopencv.com/category/opencv/), [OpenCV DNN](https://learnopencv.com/category/opencv-dnn/)\n\n\n![Face Detection - Dlib, OpenCV, and Deep Learning \\( C++ / Python \\) featured image](https://cdn.learnopencv.com/wp-content/uploads/2026/07/31023437/face-detection-opencv-dlib-and-deep-learning-c-python-featured-2026.jpg)\n  *   *   * [ ](https://bigvision.ai/expert-ai-solution-builders?utm_source=lopcv&utm_medium=post-icon)\n\n\n**Updated July 31, 2026:** The original tutorial, examples, media, narrative, and teaching order are preserved below. The labelled 2026 correction area adds only the verified API, compatibility, validation, and failure-handling changes needed for current OpenCV; where a historical snippet uses an obsolete API, the correction area is the runnable path.\nIn this tutorial, we will discuss the various Face Detection methods in OpenCV, Dlib, and Deep Learning and compare the methods quantitatively. We will share code in C++ and Python for the following Face Detectors:\n  1. Haar Cascade Face Detector in OpenCV\n  2. Deep Learning based Face Detector in OpenCV.\n  3. HoG Face Detector in Dlib\n  4. Deep Learning based Dlib Face Detection\n\n\nWe will not go into the theory of any of them and only discuss their usage. We will also share some rules of thumb on which model to prefer according to your application.\nThroughout the post, we will assume image size of 300×300.\n## 1. Haar Cascade Face Detector in OpenCV\nHaar Cascade-based Face Detector was the state-of-the-art in Face Detection for many years since 2001 when Viola and Jones introduced it. There have been many improvements in recent years. OpenCV has many Haar-based models, which can be found **[in Github](https://github.com/opencv/opencv/tree/master/data/haarcascades)**.\n### Code\nPlease download the code from the link below. We have provided code snippets throughout the blog for better understanding. You will find CPP and python files for each face detector and a separate file that compares all the methods together ( run-all.py and run-all.cpp ). We also share all the models required for running the code.\n#### Python  \n|  1 2 3 4 5 6  |  `faceCascade ``=` `cv2.CascadeClassifier(``'./haarcascade_frontalface_default.xml'``)` `faces ``=` `faceCascade.detectMultiScale(frameGray)` `for` `face ``in` `faces:` `x1, y1, w, h ``=` `face` `x2 ``=` `x1 ``+` `w` `y2 ``=` `y1 ``+` `h`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12  |  `faceCascadePath = ``\"./haarcascade_frontalface_default.xml\"``;` `faceCascade.load( faceCascadePath )` `std::vector<Rect> faces;` `faceCascade.detectMultiScale(frameGray, faces);` `for` `( ``size_t` `i = 0; i < faces.size(); i++ )` `{` `int` `x1 = faces[i].x;` `int` `y1 = faces[i].y;` `int` `x2 = faces[i].x + faces[i].width;` `int` `y2 = faces[i].y + faces[i].height;` `}`  |  \n| --- | --- |  \nThe above code snippet loads the haar cascade model file and applies it to a grayscale image. the output is a list containing the detected faces. Each list member is again a list with 4 elements indicating the (x, y) coordinates of the top-left corner and the width and height of the detected face.\n### Pros\n  1. Works almost real-time on CPU\n  2. Simple Architecture\n  3. Detects faces at different scales\n\n\n### Cons\n  1. The major drawback of this method is that it gives many false predictions.\n  2. Doesn’t work on non-frontal images.\n  3. It doesn’t work under occlusion.\n\n\n## 2. DNN Face Detector in OpenCV\nThis model was included in OpenCV from version 3.3. It is based on a Single-Shot-Multibox detector and uses ResNet-10 Architecture as the backbone. The model was trained using images from the web, but the source is not disclosed. OpenCV provides 2 models for this face detector.\n  1. Floating point 16 version of the original caffe implementation ( 5.4 MB )\n  2. 8 bit quantized version using Tensorflow ( 2.7 MB )\n\n\nWe have included both models along with the code.\n### Code\n#### Python  \n|  1 2 3 4 5 6 7 8 9  |  `DNN ``=` `\"TF\"` `if` `DNN ``=``=` `\"CAFFE\"``:` `modelFile ``=` `\"res10_300x300_ssd_iter_140000_fp16.caffemodel\"` `configFile ``=` `\"deploy.prototxt\"` `net ``=` `cv2.dnn.readNetFromCaffe(configFile, modelFile)` `else``:` `modelFile ``=` `\"opencv_face_detector_uint8.pb\"` `configFile ``=` `\"opencv_face_detector.pbtxt\"` `net ``=` `cv2.dnn.readNetFromTensorflow(modelFile, configFile)`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11  |  `const` `std::string caffeConfigFile = ``\"./deploy.prototxt\"``;` `const` `std::string caffeWeightFile = ``\"./res10_300x300_ssd_iter_140000_fp16.caffemodel\"``;` `const` `std::string tensorflowConfigFile = ``\"./opencv_face_detector.pbtxt\"``;` `const` `std::string tensorflowWeightFile = ``\"./opencv_face_detector_uint8.pb\"``;` `#ifdef CAFFE` `Net net = cv::dnn::readNetFromCaffe(caffeConfigFile, caffeWeightFile);` `#else` `Net net = cv::dnn::readNetFromTensorflow(tensorflowWeightFile, tensorflowConfigFile);` `#endif`  |  \n| --- | --- |  \nWe load the required model using the above code. If we want to use the floating point model of Caffe, we use the caffemodel and prototxt files. Otherwise, we use the quantized TensorFlow model. Also, note the difference in how we read the networks for Caffe and Tensorflow.\n#### Python  \n|  1 2 3 4 5 6 7 8 9 10 11 12  |  `blob ``=` `cv2.dnn.blobFromImage(frameOpencvDnn, ``1.0``, (``300``, ``300``), [``104``, ``117``, ``123``], ``False``, ``False``)` `net.setInput(blob)` `detections ``=` `net.forward()` `bboxes ``=` `[]` `for` `i ``in` `range``(detections.shape[``2``]):` `confidence ``=` `detections[``0``, ``0``, i, ``2``]` `if` `confidence > conf_threshold:` `x1 ``=` `int``(detections[``0``, ``0``, i, ``3``] ``*` `frameWidth)` `y1 ``=` `int``(detections[``0``, ``0``, i, ``4``] ``*` `frameHeight)` `x2 ``=` `int``(detections[``0``, ``0``, i, ``5``] ``*` `frameWidth)` `y2 ``=` `int``(detections[``0``, ``0``, i, ``6``] ``*` `frameHeight)`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25  |  `#ifdef CAFFE` `cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, ``false``, ``false``);` `#else` `cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, ``true``, ``false``);` `#endif` `net.setInput(inputBlob, ``\"data\"``);` `cv::Mat detection = net.forward(``\"detection_out\"``);` `cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<``float``>());` `for``(``int` `i = 0; i &lt; detectionMat.rows; i++)` `{` `float` `confidence = detectionMat.at&lt;``float``&gt;(i, 2);` `if``(confidence &gt; confidenceThreshold)` `{` `int` `x1 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 3) * frameWidth);` `int` `y1 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 4) * frameHeight);` `int` `x2 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 5) * frameWidth);` `int` `y2 = ``static_cast``<``int``>(detectionMat.at<``float``>(i, 6) * frameHeight);` `cv::rectangle(frameOpenCVDNN, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0),2, 4);` `}` `}`  |  \n| --- | --- |  \nIn the above code, the image is converted to a blob and passed through the network using the forward() function. The output detections is a 4-D matrix, where\n  * The 3rd dimension iterates over the detected faces. (i is the iterator over the number of faces)\n  * The fourth dimension contains information about the bounding box and the score for each face. For example, detections[0,0,0,2] gives the confidence score for the first face, and detections[0,0,0,3:6] give the bounding box.\n\n\nThe output coordinates of the bounding box are normalized between [0,1]. Thus the coordinates should be multiplied by the height and width of the original image to get the correct bounding box on the image.\n### Pros\nThe method has the following merits :\n  1. Most accurate out of the four methods\n  2. Runs at real-time on CPU\n  3. Works for different face orientations – up, down, left, right, side-face, etc.\n  4. Works even under substantial occlusion\n  5. Detects faces across various scales ( detects big as well as tiny faces )\n\n\nThe DNN-based detector overcomes all the drawbacks of the Haar cascade based detector without compromising on any benefit provided by Haar. We could not see any major drawback for this method except that it is slower than the Dlib HoG-based Face Detector discussed next.\nIt would be safe to say that it is time to bid farewell to Haar-based face detector and DNN based Face Detector should be the preferred choice in OpenCV.\n## 3. HoG Face Detector in Dlib\nThis is a widely used face detection model based on the [Histogram of Oriented Gradients](https://learnopencv.com/histogram-of-oriented-gradients/) (HoG) features and SVM. The model is built out of 5 HOG filters – front looking, left looking, right looking, front looking but rotated left, and a front looking but rotated right. The model comes embedded in the **[header file](https://github.com/davisking/dlib/blob/master/dlib/image_processing/frontal_face_detector.h)** itself.\nThe dataset used for training consists of 2825 images obtained from the LFW dataset and manually annotated by Davis King, the author of Dlib. It can be downloaded from **[here](http://dlib.net/files/data/dlib_face_detector_training_data.tar.gz)**.\n### Code\n#### Python  \n|  1 2 3 4 5 6 7  |  `hogFaceDetector ``=` `dlib.get_frontal_face_detector()` `faceRects ``=` `hogFaceDetector(frameDlibHogSmall, ``0``)` `for` `faceRect ``in` `faceRects:` `x1 ``=` `faceRect.left()` `y1 ``=` `faceRect.top()` `x2 ``=` `faceRect.right()` `y2 ``=` `faceRect.bottom()`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16  |  `frontal_face_detector hogFaceDetector = get_frontal_face_detector();` `// Convert OpenCV image format to Dlib's image format` `cv_image<bgr_pixel> dlibIm(frameDlibHogSmall);` `// Detect faces in the image` `std::vector<dlib::rectangle> faceRects = hogFaceDetector(dlibIm);` `for` `( ``size_t` `i = 0; i < faceRects.size(); i++ )` `{` `int` `x1 = faceRects[i].left();` `int` `y1 = faceRects[i].top();` `int` `x2 = faceRects[i].right();` `int` `y2 = faceRects[i].bottom();` `cv::rectangle(frameDlibHog, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (``int``)(frameHeight/150.0), 4);` `}`  |  \n| --- | --- |  \nIn the above code, we first load the face detector. Then we pass it the image through the detector. The second argument is the number of times we want to upscale the image. The more you upscale, the better the chances of detecting smaller faces. However, upscaling the image will have a substantial impact on the computation speed. The output is in the form of a list of faces with the (x, y) coordinates of the diagonal corners.\n### Pros\n  1. Fastest method on CPU\n  2. Works very well for frontal and slightly non-frontal faces\n  3. Lightweight model as compared to the other three.\n  4. Works under small occlusion\n\n\nBasically, this method works under most cases except a few, as discussed below.\n### Cons\n  1. The major drawback is that it does not detect small faces, as it is trained for a minimum face size of 80×80. Thus, you need to ensure that the face size is more than that in your application. You can, however, train your own face detector for smaller-sized faces.\n  2. The bounding box often excludes part of the forehead and even part of the chin sometimes.\n  3. It does not work very well under substantial occlusion.\n  4. It does not work for side faces and extreme non-frontal faces, like looking down or up.\n\n\n## 4. Convolutional Neural Network – CNN Face Detector in Dlib\nThis method uses a **[Maximum-Margin Object Detector ( MMOD ) with CNN-based](https://arxiv.org/pdf/1502.00046.pdf)** features. The training process for this method is very simple and you don’t need a large amount of data to train a custom object detector. For more information on training, visit the **[dlib c++ library blog](http://blog.dlib.net/2016/10/easily-create-high-quality-object.html)**.\nThe model can be downloaded from the **[dlib-models repository](https://github.com/davisking/dlib-models)**.  \nIt uses a dataset manually labeled by its Author, Davis King, consisting of images from various datasets like ImageNet, PASCAL VOC, VGG, WIDER, Face Scrub. It contains 7220 images. The dataset can be downloaded from **[here.](http://dlib.net/files/data/dlib_face_detection_dataset-2016-09-30.tar.gz)**\n### Code\n#### Python  \n|  1 2 3 4 5 6 7  |  `dnnFaceDetector ``=` `dlib.cnn_face_detection_model_v1(``\"./mmod_human_face_detector.dat\"``)` `faceRects ``=` `dnnFaceDetector(frameDlibHogSmall, ``0``)` `for` `faceRect ``in` `faceRects:` `x1 ``=` `faceRect.rect.left()` `y1 ``=` `faceRect.rect.top()` `x2 ``=` `faceRect.rect.right()` `y2 ``=` `faceRect.rect.bottom()`  |  \n| --- | --- |  \n#### C++  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  |  `String mmodModelPath = ``\"./mmod_human_face_detector.dat\"``;` `net_type mmodFaceDetector;` `deserialize(mmodModelPath) >> mmodFaceDetector;` `// Convert OpenCV image format to Dlib's image format` `cv_image<bgr_pixel> dlibIm(frameDlibMmodSmall);` `matrix<rgb_pixel> dlibMatrix;` `assign_image(dlibMatrix, dlibIm);` `// Detect faces in the image` `std::vector<dlib::mmod_rect> faceRects = mmodFaceDetector(dlibMatrix);` `for` `( ``size_t` `i = 0; i < faceRects.size(); i++ )` `{` `int` `x1 = faceRects[i].rect.left();` `int` `y1 = faceRects[i].rect.top();` `int` `x2 = faceRects[i].rect.right();` `int` `y2 = faceRects[i].rect.bottom();` `cv::rectangle(frameDlibMmod, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (``int``)(frameHeight/150.0), 4);` `}`  |  \n| --- | --- |  \nThe code is similar to the HoG detector except that, in this case, we load the CNN face detection model. Also, the coordinates are present inside a rect object.\n### Pros\n  1. Works for different face orientations\n  2. Robust to occlusion\n  3. Works very fast on GPU\n  4. Very easy training process\n\n\n### Cons\n  1. Very slow on CPU\n  2. It does not detect small faces as it is trained for a minimum face size of 80×80. Thus, you need to ensure that the face size is more than that in your application. You can, however, train your own face detector for smaller-sized faces.\n  3. The bounding box is even smaller than the HoG detector.\n\n\n## 5. Accuracy Comparison\nI tried to evaluate the 4 models using the FDDB dataset using the [script used for evaluating the OpenCV-DNN model](https://github.com/opencv/opencv/blob/master/modules/dnn/misc/face_detector_accuracy.py). However, I found surprising results. Dlib had worse numbers than Haar, although visually dlib outputs look much better. Given below are the Precision scores for the 4 methods.\n[![face detectors in opencv and dlib - graph to help understand the wrong way of comparing dlib face detection with others methods](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-coco-comparison.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-coco-comparison.jpg)\n  \nWhere,  \nAP_50 = Precision when the overlap between Ground Truth and predicted bounding box is at least 50% ( IoU = 50% )  \nAP_75 = Precision when the overlap between Ground Truth and predicted bounding box is at least 75% ( IoU = 75% )  \nAP_Small = Average Precision for small size faces ( Average of IoU = 50% to 95% )  \nAP_medium = Average Precision for medium size faces ( Average of IoU = 50% to 95% )  \nAP_Large = Average Precision for large size faces ( Average of IoU = 50% to 95% )  \nmAP = Average precision across different IoU ( Average of IoU = 50% to 95% )\n**On closer inspection, I found that this evaluation is not fair for Dlib.**\n### 5.1. Evaluating accuracy the wrong way!\nAccording to my analysis, the reasons for lower numbers for dlib are as follows :\n[![comparing the face detected by OpenCV Haar with DNN, HoG and MOOD – single face tilted to left, occluded with hair](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result1-e1539872861105.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result1-e1539872861105.jpg)[![comparing the face detected by OpenCV Haar with DNN, HoG and MOOD – single face tilted to right, light shadow of hair](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result2-e1539872827875.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095724/fd-acc-result2-e1539872827875.jpg)[![comparing the faces detected by OpenCV Haar with DNN, HoG and MOOD – multiple faces in image](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095723/fd-acc-result3-e1539872783684.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095723/fd-acc-result3-e1539872783684.jpg)\n**Thus, the only relevant metric for a fair comparison between OpenCV and Dlib is AP_50 ( or even less than 50 since we mostly compare** the number of detected faces ). However, this point should always be considered while using the Dlib Face detectors.\n## 6. Speed Comparison\nWe used a 300×300 image for the comparison of the methods. The MMOD detector can be run on a GPU, but the support for NVIDIA GPUs in OpenCV is still not there. So, we evaluate the methods on CPU only and also report results for MMOD on GPU as well as CPU.\n#### Hardware used\nProcessor : Intel Core i7 6850K – 6 Core  \nRAM : 32 GB  \nGPU : NVIDIA GTX 1080 Ti with 11 GB RAM  \nOS : Linux 16.04 LTS  \nProgramming Language : Python\nWe run each method 10000 times on the given image and take 10 such iterations and average the time taken. Given below are the results.\n[![Bar graph showing the average time taken \\(speed\\) by different methods for tests run by us \\(dlib face detection\\)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095729/face-detection-speed-comparison.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095729/face-detection-speed-comparison.jpg)\nAs you can see from the image of this size, all the methods perform in real-time, except MMOD. MMOD detector is very fast on a GPU but is very slow on a CPU.\nIt should also be noted that these numbers can be different on different systems.\n## 7. Comparison under various conditions\nApart from accuracy and speed, there are some other factors that help us decide which one to use. In this section, we will compare the methods based on various other factors which are also important.\n### 7.1. Detection Across Scale\nWe will see an example where, in the same video, the person goes back n forth, thus making the face smaller and bigger. We notice that the OpenCV DNN (Deep Neural network) detects all the faces while Dlib detects only those faces which are bigger in size. We also show the size of the detected face along with the bounding box.\n[![GIF image comparing the accuracy of face detected in video by different methods – inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-scale-comparison.gif)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/face-detection-scale-comparison.gif)\nIt can be seen that dlib based methods can detect faces of size up to ~(70×70) after which they fail to detect. As we discussed earlier, I think this is the major drawback of Dlib based methods. Since it is impossible to know the size of the face beforehand in most cases, we can get rid of this problem by upscaling the image, but then the speed advantage of dlib as compared to **OpenCV-DNN** goes away.\n### 7.2. Non-frontal Face\nNon-frontal can look towards the right, left, up, or down. Again, to be fair with dlib, we ensure the face size is more than 80×80. Given below are some examples.\n[![Comparing the face detection accuracy for non-frontal face, person looking down - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result7.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result7.jpg)[![Comparing the face detection accuracy for non-frontal face, person looking left - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result6.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095725/fd-non-frontal-result6.jpg)[![Comparing the face detection accuracy, non-frontal face when looking left down - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result5.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result5.jpg)[![Comparing the face detection accuracy, non-frontal face when looking right down - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result4.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result4.jpg)[![Comparing the face detection accuracy, non-frontal pose, 2 faces looking sideways - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result2.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095726/fd-non-frontal-result2.jpg)[![Comparing the face detection accuracy, non-frontal pose, 2 faces looking sideways - inference time is labeled for each method - cv2 cascade classifier](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-non-frontal-result1.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-non-frontal-result1.jpg)\nAs expected, **Haar** based detector fails totally. The hoG-based detector does detect faces for left or right looking faces ( since it was trained on them ) but is not as accurate as the**DNN-based** detectors of OpenCV and Dlib.\n### 7.3. Occlusion\nLet us see how well the methods perform under occlusion.\n[![Comparing the face detection accuracy, frontal pose, 2 faces, occlusion and only forehead - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/fd-occlusion-result1.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095728/fd-occlusion-result1.jpg)[![Comparing the face detection accuracy, frontal pose, singe face partly out of frame 1 - inference time is labeled for each method](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result2.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result2.jpg)[![Comparing the face detection accuracy, frontal pose, singe face partly out of frame 2 - inference time is labeled for each method - dlib face detection](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result3.jpg)](https://cdn.learnopencv.com/wp-content/uploads/2018/10/04095727/fd-occlusion-result3.jpg)\nAgain, the DNN methods outperform the other two, with OpenCV-DNN slightly better than Dlib-MMOD. This is mainly because the CNN features are much more robust than HoG or Haar features.\n## 8. Conclusion\nWe discussed the pros and cons of each method in the respective sections. I recommend trying both OpenCV-DNN and HoG methods for your application and deciding accordingly. We share some tips to get started.\n#### General Case\nIn most applications, we won’t know the face size in the image beforehand. Thus, it is better to use OpenCV – DNN method as it is pretty fast and very accurate, even for small sized faces. It also detects faces at various angles. We recommend using OpenCV-DNN in most.\n#### For medium to large image sizes\nDlib HoG is the fastest method on the CPU. But it does not detect small sized faces ( < 70×70 ). So, if you know that your application will not be dealing with very small sized faces ( for example, a selfie app ), then HoG based Face detector is a better option. Also, If you can use a GPU, then the MMOD face detector is the best option as it is very fast on GPU and provides detection at various angles.\n#### High-resolution images\nSince feeding high-resolution images is not possible with these algorithms ( for computation speed ), HoG / MMOD detectors might fail when you scale down the image. On the other hand, the OpenCV-DNN method can be used for these since it detects small faces.\nHave any other suggestions? Please mention them in the comments, and we’ll update the post accordingly!\n## Must Read Articles  \n| We have crafted the following articles especially for you.  \n1. [What is Face Detection? – The Ultimate Guide](https://learnopencv.com/what-is-face-detection-the-ultimate-guide/)  \n2. [Anti-Spoofing Face Recognition System using OAK-D and DepthAI](https://learnopencv.com/anti-spoofing-face-recognition-system-using-oak-d-and-depthai/)  \n3. [Face Recognition with ArcFace](https://learnopencv.com/face-recognition-with-arcface/)  \n4. [Face Recognition: An Introduction for Beginners](https://learnopencv.com/face-recognition-an-introduction-for-beginners/ \"Face Recognition: An Introduction for Beginners\")  |  \n| --- |  \n## References\n[[FDDB Comparison code]](https://github.com/opencv/opencv/blob/master/modules/dnn/misc/face_detector_accuracy.py)  \n[[Dlib Blog]](http://blog.dlib.net/2016/10/easily-create-high-quality-object.html)  \n[[dlib mmod python example]](http://dlib.net/cnn_face_detector.py.html)  \n[[dlib mmod cpp example]](http://dlib.net/dnn_mmod_face_detection_ex.cpp.html)  \n[[OpenCV DNN Face detector]](https://github.com/opencv/opencv/tree/master/samples/dnn/face_detector)  \n[[Haar Based Face Detector]](https://docs.opencv.org/3.4/d7/d8b/tutorial_py_face_detection.html)\n## Verified 2026 Implementation and Corrections\n**Scope of this correction:** Add YuNet and label old benchmarks historical. The material below is retained from the tested modernization only where it addresses that scope; it does not replace the original explanation or examples above.\n## Choosing YuNet as the Primary Detector\nThe original 2018 comparison included OpenCV Haar, OpenCV Caffe/TensorFlow SSD, dlib HOG, and dlib MMOD. That snapshot is historically useful, but it is not the best default dependency graph for a current OpenCV project.\nThe refreshed implementation uses [YuNet](https://doi.org/10.1007/s11633-023-1423-y), a lightweight, anchor-free face detector designed for efficient inference. OpenCV exposes it through the high-level [`FaceDetectorYN`](https://docs.opencv.org/4.x/d0/dd4/tutorial_dnn_face.html) API, so the application does not need to reproduce model-specific preprocessing or non-maximum suppression.\nThe detector roles are now explicit:  \n| Detector  | Role in this tutorial  | Default dependency?  | Output  |  \n| --- | --- | --- | --- |  \n| YuNet through `FaceDetectorYN`  | Current primary path  | Yes  | Box, five landmarks, score  |  \n| OpenCV Haar cascade  | Optional historical baseline  | No  | Box  |  \n| dlib HOG  | Optional historical baseline  | No  | Box  |  \n| dlib MMOD  | Legacy material only  | No  | Not part of the current build or tests  |  \n| OpenCV Caffe/TensorFlow SSD  | Legacy assets only  | No  | Not loaded by current programs  |  \nThe filenames `face_detection_opencv_dnn.py` and `face_detection_opencv_dnn.cpp` remain for continuity with the original tutorial. Their current implementation loads YuNet ONNX through `FaceDetectorYN`; it does not load the retained Caffe or TensorFlow SSD files.\n### 2.1 Why the dynamic-input model matters\nThe current model is `face_detection_yunet_2026may.onnx`. Its height and width are dynamic, so the program can set the network input to each decoded frame’s actual size. The [pinned OpenCV Zoo model notes](https://github.com/opencv/opencv_zoo/blob/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/README.md) explain that this export replaces fixed height and width dimensions with symbolic dimensions for variable-resolution inference, including the OpenCV 5 ONNX Runtime path.\nDynamic input does not mean unlimited accuracy at every resolution. Very small, blurred, strongly occluded, or extreme-profile faces can still be missed. It means the model contract can accept changing frame dimensions without the application pretending every source is a fixed `300×300` image.\n## Setup and Verified Model Provenance\nUse Python 3.10 or newer with NumPy and OpenCV:  \n|  1 2  |  `python3 -m pip install -r requirements.txt` `python3 download_models.py`  |  \n| --- | --- |  \nThe primary requirements are intentionally small:  \n|  1 2  |  `numpy>=1.23,<3` `opencv-python>=4.10,<6`  |  \n| --- | --- |  \nThe model downloader pins one exact OpenCV Zoo state and verifies the bytes before installing the model:  \n| Field  | Verified value  |  \n| --- | --- |  \n| Model  | `face_detection_yunet_2026may.onnx`  |  \n| Upstream  | OpenCV Zoo  |  \n| Pinned commit  | `47534e27c9851bb1128ccc0102f1145e27f23f98`  |  \n| File size  |  `229,738` bytes  |  \n| SHA-256  | `ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0`  |  \n| License  | MIT  |  \n| Copyright  | Shiqi Yu  |  \nThe exact license is recorded in the companion project’s model provenance file and in the [pinned OpenCV Zoo license](https://github.com/opencv/opencv_zoo/blob/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/LICENSE). The downloader first writes to a temporary file, checks both size and SHA-256, and only then atomically moves the verified file into `models/`. An existing model is also reverified before reuse.\nThat workflow protects against a truncated transfer or an upstream file changing while a tutorial still claims reproducible results. It is an integrity check, not a malware scanner or a substitute for reviewing model provenance.\n## The FaceDetectorYN Pipeline\nThe core pipeline has four steps:\n  1. Create the detector once.\n  2. Set the detector input size to the current frame.\n  3. Run `detect`.\n  4. validate and draw the returned rows.\n\n\n### 4.1 Create the detector once\nThe Python wrapper checks the model path and the three main post-processing parameters before constructing OpenCV’s detector:  \n|  1 2 3 4 5 6 7 8 9 10 11  |  `backend_id, target_id ``=` `backend_target(device)` `self``._model ``=` `cv2.FaceDetectorYN.create(` `str``(model_path),` `\"\",` `(``320``, ``320``),` `score_threshold,` `nms_threshold,` `top_k,` `backend_id,` `target_id,` `)`  |  \n| --- | --- |  \nThe creation size is a valid initial size. The real input size is set immediately before each detection. The refreshed defaults are:\n  * `score_threshold=0.7`: discard lower-scoring candidates.\n  * `nms_threshold=0.3`: suppress sufficiently overlapping boxes after scoring.\n  * `top_k=5000`: cap the candidates retained before non-maximum suppression.\n  * `device=cpu`: pair OpenCV’s default DNN backend with the CPU target.\n\n\nLowering the score threshold can improve recall, but it usually increases false positives and the number of candidates processed by non-maximum suppression. Tune thresholds against labeled data from the actual camera and environment.\n### 4.2 Update the size and normalize empty results\nThe model returns one 15-value row per face. OpenCV uses `None` when Python has no detections, so the wrapper converts that case into an empty array with a stable shape:  \n|  1 2 3 4 5 6  |  `height, width ``=` `frame.shape[:``2``]` `self``._model.setInputSize((width, height))` `_, faces ``=` `self``._model.detect(frame)` `if` `faces ``is` `None``:` `return` `np.empty((``0``, ``15``), dtype``=``np.float32)` `return` `np.asarray(faces, dtype``=``np.float32).reshape(``-``1``, ``15``)`  |  \n| --- | --- |  \nNormalizing the empty case keeps downstream code simple: drawing, validation, and comparison can iterate over zero or more rows without a special `None` branch.\n### 4.3 Validate before drawing\nThe tutorial’s `--validate` mode checks invariants that should remain stable across codecs and supported OpenCV versions:\n  * the result is a two-dimensional array with 15 columns;\n  * every returned value is finite;\n  * box width and height are positive;\n  * the score is in `[0, 1]`;\n  * a clipped box has valid image bounds;\n  * saved images remain readable and preserve dimensions;\n  * saved videos reopen with the expected frame count and geometry.\n\n\nThe drawing function clips boxes before rendering, writes each score, and colors the five YuNet landmarks. Clipping is a visualization safeguard. It should not be used to hide invalid detector output, which is why validation also checks the original numeric values.\n## Run Face Detection on Images and Video\nThe program runs headlessly by default. It resolves its bundled model, sample video, and output folders relative to the script rather than the shell’s current directory.\n### 5.1 Video\nProcess two frames of the bundled video, save a `720×720` MJPEG AVI, and validate it:  \n|  1 2 3 4  |  `python3 face_detection_opencv_dnn.py \\` `--max-frames 2 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe output is `output/yunet-video.avi`. A limit of zero processes the full video. The writer uses the source width, height, and frame rate; when a source reports no usable frame rate, the example uses `25` FPS as a documented fallback.\nEvery decoded frame is processed exactly once. The writer is created from the source geometry before the loop, so the old pattern of consuming a first frame merely to discover its dimensions is avoided.\n### 5.2 Image\nFor an image, choose image mode explicitly and provide a path:  \n|  1 2 3 4 5 6  |  `python3 face_detection_opencv_dnn.py \\` `--input /absolute/path/to/face-image.jpg \\` `--mode image \\` `--output-dir /absolute/path/to/results \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe saved file is `yunet-image.jpg` and has the same width, height, and channel count as the decoded input. `--mode auto` uses common image suffixes and otherwise treats the input as video.\n### 5.3 Useful controls  \n| Option  | Purpose  |  \n| --- | --- |  \n| `--model PATH`  | Use a specific YuNet ONNX file  |  \n| `--device cpu|cuda`  | Choose the DNN backend/target pair  |  \n| `--score-threshold FLOAT`  | Filter low-confidence candidates  |  \n| `--nms-threshold FLOAT`  | Control overlap suppression  |  \n| `--top-k INTEGER`  | Limit candidates before NMS  |  \n| `--max-frames INTEGER`  | Bound video work for tests or previews  |  \n| `--display`  | Open an interactive window  |  \n| `--no-display`  | Make headless intent explicit  |  \n| `--validate`  | Check detections and saved output  |  \nCPU is the tested default. CUDA support depends on how OpenCV was built and was not part of this article’s regression matrix.\n## Compare YuNet, Haar, and dlib HOG\nThe comparison program defaults to YuNet alone, so it does not import dlib or require Haar. Optional detectors are created only when requested:  \n|  1 2 3 4 5  |  `python3 run-all.py \\` `--detectors yunet,haar \\` `--max-frames 1 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nEach detector receives the same original frame. Its annotated panel keeps the original `W×H` size, and the panels are concatenated horizontally. Two detectors therefore produce a `2W×H` frame. On the `720×720` fixture, the tested YuNet-plus-Haar comparison wrote `1440×720`, with two YuNet detections and one Haar detection.\nThat single frame is regression evidence, not an accuracy ranking. A meaningful detector comparison needs a labeled dataset, a fixed matching policy, precision-recall metrics, and representative pose, scale, lighting, and occlusion.\n### 6.1 Haar cascade\nHaar remains useful for teaching classical cascaded detection and for constrained frontal-face scenarios. The optional wrapper resizes to a fixed height, converts to grayscale, detects faces, and scales each box back independently in `x` and `y`.\nThe C++ Haar target is built only with OpenCV 4. In the tested OpenCV 5 configuration, the historical `CascadeClassifier` path is not available through the core API used by this project, so CMake disables that target. Python reports a clear error if its OpenCV binding lacks `CascadeClassifier`.\n### 6.2 dlib HOG\ndlib’s frontal detector is a HOG-pyramid detector with five embedded filters for frontal, side-looking, and rotated-frontal views, as documented in the [official dlib source](https://dlib.net/dlib/image_processing/frontal_face_detector.h.html). Install it only when you want this baseline:  \n|  1 2 3 4 5  |  `python3 -m pip install -r requirements-dlib.txt` `python3 face_detection_dlib_hog.py \\` `--max-frames 2 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe Python import is lazy, and the C++ targets are added only when CMake finds `dlib::dlib`. The current default path never unpacks the historical `dlib.zip`. dlib was not installed in the validation environment, so its actual detection output was not tested for this refresh; only the clear missing-dependency behavior and CMake’s clean disable path were checked.\n## Build and Run the C++ Program\nThe C++ project requires CMake 3.16 or newer, a C++17 compiler, and OpenCV 4.10 or newer but earlier than 6:  \n|  1 2 3  |  `cmake -S . -B build -DCMAKE_BUILD_TYPE=Release` `cmake --build build --parallel` `ctest --test-dir build --output-on-failure`  |  \n| --- | --- |  \nRun the primary video path:  \n|  1 2 3 4  |  `./build/face_detection_opencv_dnn \\` `--max-frames 2 \\` `--no-display \\` `--validate`  |  \n| --- | --- |  \nThe C++ detector uses the same API and parameters as Python:  \n|  1 2 3 4 5 6 7 8 9 10 11 12 13  |  `model_ = cv::FaceDetectorYN::create(` `model_path.string(),` `\"\"``,` `cv::Size(320, 320),` `score_threshold,` `nms_threshold,` `top_k,` `backend_id,` `target_id);` `model_->setInputSize(frame.size());` `cv::Mat faces;` `model_->detect(frame, faces);`  |  \n| --- | --- |  \nEach `CV_32F` row must have 15 columns. The wrapper copies the first four values into a rectangle, the next ten into five landmarks, and the final value into the score. Both language paths then share the same conceptual validation and output contract.\nAll default C++ targets compile with strict warnings treated as errors on Clang and GCC. Tests are registered only after the verified model exists, which turns a missing setup step into a clear configure-time error.\n## Tested Results\nThe refresh was tested from unrelated working directories so that accidental dependence on the caller’s current folder would fail.  \n| Path  | Environment  | Result  |  \n| --- | --- | --- |  \n| Python tests  | Python 3.14.3, OpenCV 4.13.0  |  `5/5` passed  |  \n| C++ tests  | OpenCV 4.12.0, C++17  |  `2/2` CTests passed  |  \n| Python tests  | Official OpenCV 5.0.0 build  |  `5/5` passed  |  \n| C++ tests  | Official OpenCV 5.0.0 build, C++17  |  `2/2` CTests passed  |  \nThe stable fixture results were:\n  * one `720×720` image: exactly two YuNet faces;\n  * two video frames: `720×720`, exactly two frames saved, four YuNet detections in total;\n  * YuNet-only comparison: `720×720`, two frames, four detections in total;\n  * YuNet plus Haar on one OpenCV 4 frame: `1440×720`, two YuNet detections and one Haar detection;\n  * a missing input returns exit code `2` with a specific read/open error;\n  * the model size and SHA-256 checks pass before inference.\n\n\nImage and video tests assert dimensions, frame counts, valid boxes, finite landmarks, confidence bounds, and readable output. They do not compare encoded JPEG or AVI bytes, because codec output can vary even when decoded geometry and detections are correct.\nExact OpenCV 4.14 was not available in the local validation environment. It remains the intended OpenCV 4 release target, but this handoff does not claim an exact 4.14 run. The OpenCV 5 build used for testing did not include ONNX Runtime, so OpenCV’s native DNN fallback was exercised rather than the OpenCV 5 ONNX Runtime engine.\n### From idea to working model to real-time deployment\nBig Vision takes computer vision projects through the full journey, not just the easy parts.\n![Satya Mallick](https://opencv.org/university/wp-content/uploads/sites/4/2023/04/Dr-Satya.jpg)\n**Satya Mallick** Founder - Big Vision & LearnOpenCV\n[ Talk to our Team ](https://bigvision.ai/expert-ai-solution-builders/)\n## Limitations and Production Guidance\n### 9.1 Measure on your data\nThe two-face fixture proves a stable execution path, not broad accuracy. Build a labeled validation set that includes the smallest expected face, motion blur, masks, glasses, partial occlusion, profile views, backlighting, skin-tone diversity, camera compression, and realistic non-face negatives. Measure precision and recall over threshold choices instead of choosing `0.7` from one screenshot.\n### 9.2 Detection is frame-local\nThe example detects every frame independently. It does not attach persistent identities, smooth boxes, or bridge missed detections. For video analytics, add a tracker and define when a track is created, confirmed, lost, and retired.\n### 9.3 Landmarks are sparse\nYuNet’s five points can support coarse alignment. Applications that need eye contours, expression geometry, dense face meshes, or robust pose estimation should use a dedicated landmark model after detection.\n### 9.4 Backend support is build-specific\n`--device cuda` works only when the installed OpenCV DNN build supports the requested CUDA backend and target. OpenCV 5 can also use an ONNX Runtime engine for the dynamic model, but that exact engine was not present in this test build. Benchmark the precise OpenCV package, backend, target, model, resolution, and hardware that will ship.\n### 9.5 Treat privacy and misuse as engineering requirements\nFaces are personal data in many contexts. Minimize collection, document retention, protect stored media, and obtain appropriate consent. A detector’s confidence score is not proof of identity, age, emotion, intent, or liveness.\nWas This Article Helpful?\nPost Views: 123\n## Subscribe & Download Code\nIf you liked this article and would like to download code (C++ and Python) and example images used in this post, please [click here](javascript:void\\(0\\)). In our newsletter, we share Computer Vision and AI tutorials and examples written in C++/Python, and Computer Vision and Machine Learning algorithms and news.  \n  \n\n[ Download Example Code](javascript:void\\(0\\))\n  \n  \n\n[PrevPreviousKatharsis : A Software Engineer’s first steps in Computer Vision and Machine Learning](https://learnopencv.com/katharsis-software-engineers-first-step-in-cvml/)\n[NextInstall OpenCV from source on Windows – C++ / PythonNext](https://learnopencv.com/install-opencv-4-on-windows/)\n###  [ Train RF-DETR for Instance Segmentation with GPT-6 Astra ](https://learnopencv.com/astra-rf-detr-microduck-segmentation/)\nBefore a flight, I left Astra a short prompt and a signed-in Roboflow account. It\n###  [ How 10x AI Engineers Train Models for Production: Lessons from PINTO’s Face Alignment Project ](https://learnopencv.com/how-10x-ai-engineers-train-models-for-production/)\nLearn a production model training playbook from PINTO’s face alignment project: reframe the task, engineer\n###  [ VGGT vs. VGGT-Ω (VGGT-Omega): A Complete Guide to Feed-Forward 3D Reconstruction ](https://learnopencv.com/vggt-vs-vggt-%cf%89-vggt-omega-a-complete-guide-to-feed-forward-3d-reconstruction/)\nHow VGGT and VGGT-Ω work, what changed, and real benchmark numbers, speed, GPU memory, depth,\n![Satya Mallick](https://opencv.org/university/wp-content/uploads/sites/4/2023/04/Dr-Satya.jpg)\n#### Satya Mallick, Ph.D.\nFounder - Big Vision & LearnOpenCV\n#####  Are you struggling with your Computer Vision Product Development?\nHelping startups and enterprises build and deploy scalable solutions that work in the real world.\n[ Schedule a Call ](https://bigvision.ai/expert-ai-solution-builders?utm_source=lopcv&utm_medium=post)\n####  Table of Contents\n  1. [1. Haar Cascade Face Detector in OpenCV](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-0)\n  2. [2. DNN Face Detector in OpenCV](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-1)\n  3. [3. HoG Face Detector in Dlib](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-2)\n  4. [4. Convolutional Neural Network – CNN Face Detector in Dlib](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-3)\n  5. [5. Accuracy Comparison](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-4)\n  6. [6. Speed Comparison](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-5)\n  7. [7. Comparison under various conditions](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-6)\n  8. [8. Conclusion](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-7)\n  9. [Must Read Articles](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-8)\n  10. [References](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#elementor-toc__heading-anchor-9)\n  11. [Verified 2026 Implementation and Corrections](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#verified-2026-implementation-and-corrections)\n  12. [Choosing YuNet as the Primary Detector](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-2-choosing-yunet-as-the-primary-detector)\n  13. [Setup and Verified Model Provenance](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-3-setup-and-verified-model-provenance)\n  14. [The FaceDetectorYN Pipeline](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-4-the-facedetectoryn-pipeline)\n  15. [Run Face Detection on Images and Video](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-5-run-face-detection-on-images-and-video)\n  16. [Compare YuNet, Haar, and dlib HOG](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-6-compare-yunet-haar-and-dlib-hog)\n  17. [Build and Run the C++ Program](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-7-build-and-run-the-c-program)\n  18. [Tested Results](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-8-tested-results)\n  19. [Limitations and Production Guidance](https://learnopencv.com/face-detection-opencv-dlib-and-deep-learning-c-python/#update-2026-9-limitations-and-production-guidance)\n\n\nWas This Article Helpful?\n  * [C++](https://learnopencv.com/tag/c/), [cascadeClassifier](https://learnopencv.com/tag/cascade-classifier/), [Comparison](https://learnopencv.com/tag/comparison/), [cv2.CascadeClassifier](https://learnopencv.com/tag/cv2-cascadeclassifier/), [cv2.dnn](https://learnopencv.com/tag/cv2-dnn/), [cv2.dnn.blobFromImage](https://learnopencv.com/tag/cv2-dnn-blobfromimage/), [cv2.dnn.readNetFromCaffe](https://learnopencv.com/tag/cv2-dnn-readnetfromcaffe/), [cv2.dnn.readNetFromTensorflow](https://learnopencv.com/tag/cv2-dnn-readnetfromtensorflow/), [dlib.cnn_face_detection_model_v1](https://learnopencv.com/tag/dlib-cnn_face_detection_model_v1/), [dlib.get_frontal_face_detector](https://learnopencv.com/tag/dlib-get_frontal_face_detector/), [dnnFaceDetector](https://learnopencv.com/tag/dnnfacedetector/), [evaluation](https://learnopencv.com/tag/evaluation/), [faceDetector](https://learnopencv.com/tag/facedetector/), [haarCascade](https://learnopencv.com/tag/haarcascade/), [HOG](https://learnopencv.com/tag/hog/), [hogFaceDetector](https://learnopencv.com/tag/hogfacedetector/), [mmodFaceDetector](https://learnopencv.com/tag/mmodfacedetector/), [performanceComparision](https://learnopencv.com/tag/performancecomparision/), [Python](https://learnopencv.com/tag/python/), [readNetFromCaffe](https://learnopencv.com/tag/readnetfromcaffe/), [readNetFromTensorflow](https://learnopencv.com/tag/readnetfromtensorflow/), [tensorflow](https://learnopencv.com/tag/tensorflow/)\n\n\n## Read Next\n[ ![Decoding Virat Kohli’s Flick Shot: AI-Based 3D Motion Reconstruction](https://cdn.learnopencv.com/wp-content/uploads/2026/07/16015539/decoding-virat-kohli-flick-shot-3d-motion-reconstruction.png) ](https://learnopencv.com/decoding-virat-kohlis-flick-shot-ai-based-3d-motion-reconstruction/)\n[3D Computer Vision](https://learnopencv.com/category/3d-computer-vision/)[3D Reconstruction](https://learnopencv.com/category/3d-computer-vision/3d-reconstruction/)[Segmentation](https://learnopencv.com/category/segmentation/)[SpatialAI-Depth](https://learnopencv.com/category/3d-computer-vision/spatialai-depth/)[Video Analysis](https://learnopencv.com/category/video-analysis/)\n[Adnan Shaikh](https://learnopencv.com/author/adnan/) July 18, 2026 \n##  [ Decoding Virat Kohli’s Flick Shot: AI-Based 3D Motion Reconstruction ](https://learnopencv.com/decoding-virat-kohlis-flick-shot-ai-based-3d-motion-reconstruction/)\nReconstruct the 3D swing plane of Virat Kohli's flick shot from a single 2D video with off-the-shelf vision models. No…\n[ ![How to Run Object Detection with OpenCV 5](https://cdn.learnopencv.com/wp-content/uploads/2026/07/11002616/OpenCV_5_Blog_Thumbnail_final-scaled.jpg) ](https://learnopencv.com/how-to-run-object-detection-with-opencv-5/)\n[Object Detection](https://learnopencv.com/category/object-detection/)[OpenCV 5](https://learnopencv.com/category/opencv/opencv-5/)[OpenCV DNN](https://learnopencv.com/category/opencv-dnn/)[YOLO](https://learnopencv.com/category/yolo/)\n[Sudip Chakrabarty](https://learnopencv.com/author/sudip/) July 9, 2026 \n##  [ How to Run Object Detection with OpenCV 5 ](https://learnopencv.com/how-to-run-object-detection-with-opencv-5/)\nLearn about the new OpenCV 5 and how to use its DNN engine to run object detection models on the…\n[ ![How to Fine-Tune YOLO26 for Safety Gear and Sign Language Detection](https://cdn.learnopencv.com/wp-content/uploads/2026/06/17235330/YOLO26_Finetuning_Thumbnail_image-768x512.jpg) ](https://learnopencv.com/how-to-fine-tune-yolo26-for-safety-gear-and-sign-language-detection/)\n[Computer Vision](https://learnopencv.com/category/computer-vision/)[Object Detection](https://learnopencv.com/category/object-detection/)[YOLO](https://learnopencv.com/category/yolo/)\n[Sudip Chakrabarty](https://learnopencv.com/author/sudip/) June 18, 2026 \n##  [ How to Fine-Tune YOLO26 for Safety Gear and Sign Language Detection ](https://learnopencv.com/how-to-fine-tune-yolo26-for-safety-gear-and-sign-language-detection/)\nLearn how to fine-tune YOLO26 on your own data. We build a construction PPE safety detector and a sign-language reader…\n##  Subscribe to our Newsletter\nSubscribe to our email newsletter to get the latest posts delivered right to your email.\nName \nEmail \nSend\n![](https://cdn.learnopencv.com/wp-content/uploads/2025/12/04080755/learnOpenCV_by_bigvision1.png)\nEmpowering innovation through education, LearnOpenCV provides in-depth tutorials, code, and guides in AI, Computer Vision, and Deep Learning. Led by Dr. Satya Mallick, we're dedicated to nurturing a community keen on technology breakthroughs.\n[ Read More ](https://learnopencv.com/about/)\nCategories\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/)\n  * [Object Detection](https://learnopencv.com/category/object-detection/)\n  * [Image Classification](https://learnopencv.com/category/image-classification)\n  * [YOLO](https://learnopencv.com/category/yolo/)\n  * [Image Processing](https://learnopencv.com/category/image-processing/)\n  * [Image Segmentation](https://learnopencv.com/category/image-segmentation/)\n\n\n  * [Deep Learning](https://learnopencv.com/category/deep-learning/)\n  * [Object Detection](https://learnopencv.com/category/object-detection/)\n  * [Image Classification](https://learnopencv.com/category/image-classification)\n  * [YOLO](https://learnopencv.com/category/yolo/)\n  * [Image Processing](https://learnopencv.com/category/image-processing/)\n  * [Image Segmentation](https://learnopencv.com/category/image-segmentation/)\n\n\nGetting Started\n  * [Installation](https://learnopencv.com/category/install/)\n  * [PyTorch](https://learnopencv.com/learn-pytorch/)\n  * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n  * [Keras & Tensorflow](https://learnopencv.com/learn-keras-and-tensorflow/)\n\n\n  * [Installation](https://learnopencv.com/category/install/)\n  * [PyTorch](https://learnopencv.com/learn-pytorch/)\n  * [Getting Started with OpenCV](https://learnopencv.com/getting-started-with-opencv/)\n  * [Keras & Tensorflow](https://learnopencv.com/learn-keras-and-tensorflow/)\n\n\nBig Vision\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=footer)\n  * [Case Studies](https://bigvision.ai/case-studies/?utm_source=locv&utm_medium=footer)\n  * [Get in Touch](https://bigvision.ai/contact-us/?utm_source=locv&utm_medium=footer)\n\n\n  * [AI Consulting](https://bigvision.ai/expert-ai-solution-builders/#talk?utm_source=locv&utm_medium=footer)\n  * [Case Studies](https://bigvision.ai/case-studies/?utm_source=locv&utm_medium=footer)\n  * [Get in Touch](https://bigvision.ai/contact-us/?utm_source=locv&utm_medium=footer)\n\n\nCopyright © 2026 – BIG VISION LLC [Privacy Policy](https://learnopencv.com/privacy-policy/) [Terms and Conditions](https://learnopencv.com/terms-and-conditions/)\n  * [ ](https://bit.ly/Facebook_LearnOpenCV)\n  * [ ](https://www.instagram.com/learnopencv/)\n  * [ ](https://www.linkedin.com/in/satyamallick/)\n  * [ ](https://x.com/LearnOpenCV)\n  * [ ](https://www.youtube.com/c/LearnOpenCV?utm_source=lopcv&utm_medium=footer&utm_campaign=yt)\n\n\n[ ![](https://learnopencv.com/wp-content/uploads/2021/10/cropped-favicon-512x512-1.png) Click here to download the source code to this post ](javascript:void\\(0\\))\n",
  "body_base_path": "attachments/739daab46816/pages/",
  "body_markdown_path": "attachments/739daab46816/pages/archived-body.md",
  "local_html": "attachments/739daab46816/pages/archived-body.html",
  "body_source": "prior_capture"
}