Life2Coding
Face Detection on Images using OpenCV Haar Cascades

This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply it in various aspects using some examples. Then the output will be shown with some comparisons as well.

Requirements:

First, you need to setup your Python Environment with OpenCV. You can easily do it by following Life2Coding’s tutorial on YouTube: Linking OpenCV 3 with Python 3

Goals:

In this tutorial, I will show you how to detect faces on images using OpenCV Haar Cascades and Python coding.

Documentation:

Python: cv2.CascadeClassifier.detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]])→ objects

Detects objects of different sizes in the input image. The detected objects are returned as a list of rectangles

Parameters:          

  • cascade – Haar classifier cascade (OpenCV 1.x API only). It can be loaded from XML or YAML file using Load(). When the cascade is not needed anymore, release it using cvReleaseHaarClassifierCascade(&cascade).
  • image – Matrix of the type CV_8U containing an image where objects are detected.
  • objects – Vector of rectangles where each rectangle contains the detected object, the rectangles may be partially outside the original image.
  • numDetections – Vector of detection numbers for the corresponding objects. An object’s number of detections is the number of neighboring positively classified rectangles that were joined together to form the object.
  • scaleFactor – Parameter specifying how much the image size is reduced at each image scale.
  • minNeighbors – Parameter specifying how many neighbors each candidate rectangle should have to retain it.
  • flags – Parameter with the same meaning for an old cascade as in the function cvHaarDetectObjects. It is not used for a new cascade.
  • minSize – Minimum possible object size. Objects smaller than that are ignored.
  • maxSize – Maximum possible object size. Objects larger than that are ignored.

Steps:

  • Load the face image using cv2.imread()
  • Load the Face Haar Cascade file using cv2.CascadeClassifier()
  • Detects the face on the image using cv2.CascadeClassifier.detectMultiScale()
  • Draw boundary around the face using cv2.rectangle()
  • Display Image using cv2.imshow()
  • Save the output in an image file using cv2.imwrite()
  • Wait for keyboard button press using cv2.waitKey()
  • Exit window and destroy all windows using cv2.destroyAllWindows()

Example Code:

import cv2

scale_factor = 1.1
min_neighbors = 3
min_size = (30, 30)

def detect(path):
    img = cv2.imread(path)
    cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
    rects = cascade.detectMultiScale(img, scaleFactor=scale_factor, minNeighbors=min_neighbors,
                                          minSize=min_size)

    #if at least 1 face detected
    if len(rects) >= 0:
        # create the bounding box around the detected face
        for (x, y, w, h) in rects:
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
        cv2.imshow("Face Detection", img)
        cv2.imwrite('detected.jpg', img)
        cv2.waitKey(0)  # wait for user input to display the detected face
        cv2.destroyAllWindows()
    else:
        return [], img


def main():
    detect("hanif.jpg")


if __name__ == "__main__":
    main()

Output:

Capture Face Detection on Images using OpenCV Haar Cascades

life2coding_icon [] Face Detection on Images using OpenCV Haar Cascades

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.