{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Face classification using Haar-like feature descriptor\n\nHaar-like feature descriptors were successfully used to implement the first\nreal-time face detector [1]_. Inspired by this application, we propose an\nexample illustrating the extraction, selection, and classification of Haar-like\nfeatures to detect faces vs. non-faces.\n\n## Notes\n\nThis example relies on [scikit-learn](https://scikit-learn.org/) for feature\nselection and classification.\n\n## References\n\n.. [1] Viola, Paul, and Michael J. Jones. \"Robust real-time face\n       detection.\" International journal of computer vision 57.2\n       (2004): 137-154.\n       https://www.merl.com/publications/docs/TR2004-043.pdf\n       :DOI:`10.1109/CVPR.2001.990517`\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from time import time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\n\nimport skimage as ski"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The procedure to extract the Haar-like features from an image is relatively\nsimple. Firstly, a region of interest (ROI) is defined. Secondly, the\nintegral image within this ROI is computed. Finally, the integral image is\nused to extract the features.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "def extract_feature_image(img, feature_type, feature_coord=None):\n    \"\"\"Extract the haar feature for the current image\"\"\"\n    ii = ski.transform.integral_image(img)\n    return ski.feature.haar_like_feature(\n        ii,\n        0,\n        0,\n        ii.shape[0],\n        ii.shape[1],\n        feature_type=feature_type,\n        feature_coord=feature_coord,\n    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We use a subset of CBCL dataset which is composed of 100 face images and\n100 non-face images. Each image has been resized to a ROI of 19 by 19\npixels. We select 75 images from each group to train a classifier and\ndetermine the most salient features. The remaining 25 images from each\nclass are used to assess the performance of the classifier.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "images = ski.data.lfw_subset()\n# To speed up the example, extract the two types of features only\nfeature_types = ['type-2-x', 'type-2-y']\n\n# Compute the result\nt_start = time()\nX = [extract_feature_image(img, feature_types) for img in images]\nX = np.stack(X)\ntime_full_feature_comp = time() - t_start\n\n# Label images (100 faces and 100 non-faces)\ny = np.array([1] * 100 + [0] * 100)\n\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, train_size=150, random_state=0, stratify=y\n)\n\n# Extract all possible features\nfeature_coord, feature_type = ski.feature.haar_like_feature_coord(\n    width=images.shape[2], height=images.shape[1], feature_type=feature_types\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "A random forest classifier can be trained in order to select the most\nsalient features, specifically for face classification. The idea is to\ndetermine which features are most often used by the ensemble of trees.\nBy using only the most salient features in subsequent steps, we can\ndrastically speed up the computation while retaining accuracy.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# Train a random forest classifier and assess its performance\nclf = RandomForestClassifier(\n    n_estimators=1000, max_depth=None, max_features=100, n_jobs=-1, random_state=0\n)\nt_start = time()\nclf.fit(X_train, y_train)\ntime_full_train = time() - t_start\nauc_full_features = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])\n\n# Sort features in order of importance and plot the six most significant\nidx_sorted = np.argsort(clf.feature_importances_)[::-1]\n\nfig, axes = plt.subplots(3, 2)\nfor idx, ax in enumerate(axes.ravel()):\n    image = images[0]\n    image = ski.feature.draw_haar_like_feature(\n        image, 0, 0, images.shape[2], images.shape[1], [feature_coord[idx_sorted[idx]]]\n    )\n    ax.imshow(image)\n    ax.set_xticks([])\n    ax.set_yticks([])\n\n_ = fig.suptitle('The most important features')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can select the most important features by checking the cumulative sum\nof the feature importance. In this example, we keep the features\nrepresenting 70% of the cumulative value (which corresponds to using only 3%\nof the total number of features).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "cdf_feature_importances = np.cumsum(clf.feature_importances_[idx_sorted])\ncdf_feature_importances /= cdf_feature_importances[-1]  # divide by max value\nsig_feature_count = np.count_nonzero(cdf_feature_importances < 0.7)\nsig_feature_percent = round(sig_feature_count / len(cdf_feature_importances) * 100, 1)\nprint(\n    f'{sig_feature_count} features, or {sig_feature_percent}%, '\n    f'account for 70% of branch points in the random forest.'\n)\n\n# Select the determined number of most informative features\nfeature_coord_sel = feature_coord[idx_sorted[:sig_feature_count]]\nfeature_type_sel = feature_type[idx_sorted[:sig_feature_count]]\n# Note: it is also possible to select the features directly from the matrix X,\n# but we would like to emphasize the usage of `feature_coord` and `feature_type`\n# to recompute a subset of desired features.\n\n# Compute the result\nt_start = time()\nX = [extract_feature_image(img, feature_type_sel, feature_coord_sel) for img in images]\nX = np.stack(X)\ntime_subs_feature_comp = time() - t_start\n\ny = np.array([1] * 100 + [0] * 100)\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, train_size=150, random_state=0, stratify=y\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Once the features are extracted, we can train and test a new classifier.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "t_start = time()\nclf.fit(X_train, y_train)\ntime_subs_train = time() - t_start\n\nauc_subs_features = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])\n\nsummary = (\n    f'Computing the full feature set took '\n    f'{time_full_feature_comp:.3f}s, '\n    f'plus {time_full_train:.3f}s training, '\n    f'for an AUC of {auc_full_features:.2f}. '\n    f'Computing the restricted feature set took '\n    f'{time_subs_feature_comp:.3f}s, plus {time_subs_train:.3f}s '\n    f'training, for an AUC of {auc_subs_features:.2f}.'\n)\n\nprint(summary)\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
}