{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Face detection using a cascade classifier\n\nThis computer vision example shows how to detect faces on an image using object\ndetection framework based on machine learning.\n\nFirst, you will need an xml file, from which the trained data can be read.  The\nframework works with files, trained using Multi-block Local Binary Patterns\nFeatures (See [MB-LBP](plot_multiblock_local_binary_pattern.html)) and Gentle\nAdaboost with attentional cascade. So, the detection framework will also work\nwith [xml files from OpenCV](https://github.com/opencv/opencv/tree/master/data/lbpcascades).  There you\ncan find files that were trained to detect cat faces, profile faces and other\nthings.  But if you want to detect frontal faces, the respective file is\nalready included in scikit-image.\n\nNext you will have to specify the parameters for the ``detect_multi_scale``\nfunction. Here you can find the meaning of each of them.\n\nFirst one is ``scale_ratio``. To find all faces, the algorithm does the search\non multiple scales. This is done by changing the size of searching window. The\nsmallest window size is the size of window that was used in training. This size\nis specified in the xml file with trained parameters. The ``scale_ratio``\nparameter specifies by which ratio the search window is increased on each\nstep. If you increase this parameter, the search time decreases and the\naccuracy decreases. So, faces on some scales can be not detected.\n\n``step_ratio`` specifies the step of sliding window that is used to search for\nfaces on each scale of the image. If this parameter is equal to one, then all\nthe possible locations are searched. If the parameter is greater than one, for\nexample, two, the window will be moved by two pixels and not all of the\npossible locations will be searched for faces. By increasing this parameter we\ncan reduce the working time of the algorithm, but the accuracy will also be\ndecreased.\n\n``min_size`` is the minimum size of search window during the scale\nsearch. ``max_size`` specifies the maximum size of the window. If you know the\nsize of faces on the images that you want to search, you should specify these\nparameters as precisely as possible, because you can avoid doing expensive\ncomputations and possibly decrease the amount of false detections. You can save\na lot of time by increasing the ``min_size`` parameter, because the majority of\ntime is spent on searching on the smallest scales.\n\n``min_neighbor_number`` and ``intersection_score_threshold`` parameters are\nmade to cluster the excessive detections of the same face and to filter out\nfalse detections.  True faces usually have a lot of detections around them and\nfalse ones usually have single detection. First algorithm searches for\nclusters: two rectangle detections are placed in the same cluster if the\nintersection score between them is larger then\n``intersection_score_threshold``. The intersection score is computed using the\nequation (intersection area) / (small rectangle ratio). The described\nintersection criteria was chosen over intersection over union to avoid a corner\ncase when small rectangle inside of a big one has small intersection score.\nThen each cluster is thresholded using ``min_neighbor_number`` parameter which\nleaves the clusters that have a same or bigger number of detections in them.\n\nYou should also take into account that false detections are inevitable and if\nyou want to have a really precise detector, you will have to train it yourself\nusing [OpenCV train cascade utility](https://docs.opencv.org/2.4/doc/user_guide/ug_traincascade.html).\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import skimage as ski\n\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\n\n# Load the trained file from the module root.\ntrained_file = ski.data.lbp_frontal_face_cascade_filename()\n\n# Initialize the detector cascade.\ndetector = ski.feature.Cascade(trained_file)\n\nimg = ski.data.astronaut()\n\ndetected = detector.detect_multi_scale(\n    img=img, scale_factor=1.2, step_ratio=1, min_size=(60, 60), max_size=(123, 123)\n)\n\nfig, ax = plt.subplots()\nax.imshow(img, cmap='gray')\n\nfor patch in detected:\n    ax.axes.add_patch(\n        patches.Rectangle(\n            (patch['c'], patch['r']),\n            patch['width'],\n            patch['height'],\n            fill=False,\n            color='r',\n            linewidth=2,\n        )\n    )\n\nplt.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}