25 Lines of Python Code for Face Detection-OpenCV Technical Tutorial

25 Lines of Python Code for Face Detection-OpenCV Technical Tutorial

OpenCV is the most popular computer vision library. It was originally developed in C and C ++ and now supports Python.

OpenCV

OpenCV is the most popular computer vision library. It was originally developed in C and C ++ and now supports Python.

It uses machine learning algorithms to search a person's face in an image. For something as complex as a human face, there is no simple detection that can make a conclusion as to whether a human face exists, and thousands of feature matches are required. The algorithm breaks down the face recognition task into thousands of small tasks, each of which is not difficult to handle. These tasks are also called classifiers.

For objects similar to faces, you may need no less than 6000 classifiers, each of which needs to be successfully matched (of course, with a fault tolerance rate) to detect a face. But there is a problem: for face recognition, the algorithm calculates data blocks from the upper left corner and keeps asking "Is this a face?" There are more than 6000 tests per data block, and the amount of calculations will reach millions of levels. The computer is likely to make you wait for all the flowers.

OpenCV uses cascades to avoid this. What is Cascade? The best answer is already in the dictionary: a waterfall or a continuous waterfall.

Like a continuous waterfall, OpenCV cascade breaks down the face detection problem into several steps. For each data block, it performs a rough, fast detection. If it passes, a more careful test will be performed, and so on. The algorithm has 30 to 50 such stages, or cascades. Only through all stages can the algorithm determine that a face is detected. The advantage of this is that most graphs generate negative feedback in the first few steps, so the algorithm does not need to test all 6000 features on it, which greatly saves time. Compared to the "normal process", which takes several hours, this can realize face detection in real time.

Cascade in practice

Its theory may sound complicated, but it is actually very simple to operate. These cascades are just a series of XML files containing OpenCV data. You use the cascade initialization code you want, and it will do what you want for you.

Due to the universality of face recognition, OpenCV has a series of built-in cascades that can detect various things, from eyes to hands to legs. There are even cascades for non-human objects. For example, if you run a fruit shop that sells bananas and want to monitor people who steal bananas, one guy has developed an algorithm for this scenario !

Install OpenCV

First, you need to find the correct settings file for your operating system .

I found that installing OpenCV was the hardest part. If you encounter strange, unexplainable errors, there may be a library crash, 32- and 64-bit compatibility issues, and so on. Personal experience is that it is easiest to install OpenCV from scratch using only a Linux virtual machine.

Once installed, you can open a Python session and type the following code to test if it works:

$ python

>>> import cv2

>>>

If no errors pop up, you can go to the next link.

Understanding the code

The source code can be downloaded from the repository . Remember to get the face_detect.py text, abba.png image and haarcascade_frontalface_default.xml. Below, I break the code down.

# Get user supplied values

imagePath = sys.argv [1]

cascPath = sys.argv [2]

Pass the image and cascade name as command line arguments. We will use Abba images and the default cascade provided by OpenCV for face detection.

# Create the haar cascade

faceCascade = cv2.CascadeClassifier (cascPath)

Now we create a cascade and initialize it with the face cascade. This face cascade is imported into memory, so it is ready to use. Remember that the cascade is just an XML file containing the face detection data.

# Read the image

image = cv2.imread (imagePath)

gray = cv2.cvtColor (image, cv2.COLOR_BGR2GRAY)

Read the picture and convert it to grayscale format.

# Detect faces in the image

faces = faceCascade.detectMultiScale (    

gray,    

scaleFactor = 1.1,    

minNeighbors = 5,    

minSize = (30, 30),   

flags = cv2.cv.CV_HAAR_SCALE_IMAGE

)

What this function does is detect faces, which is the core part of the code. So let's go over the options.

The DetectMultiScale function is a general function for detecting objects. We call it on the face cascade, and it detects the face. The first option is a grayscale picture.

The second is scaleFactor. Some faces are closer to the camera and larger than others. ScaleFactor compensates for this.

The detection algorithm uses moving windows to detect objects. Before the system announces that a face is detected, minNeighbors defines how many objects are currently around it. MinSize gives the size of each window.

I use the values commonly used in these fields. In reality, you will experiment with parameters such as window size and expansion factor until you find the most suitable one.

When the function thinks it finds a face, it returns a rectangular list. Next, we loop until it thinks something is detected.

print "Found {0} faces!". format (len (faces))

# Draw a rectangle around the faces

for (x, y, w, h) in faces:

    cv2.rectangle (image, (x, y), (x + w, y + h), (0, 255, 0), 2)

The function returns four values: the x and y coordinates of the rectangle, and its height and width. We use these values and the built-in rectangle () function to draw a matrix.

cv2.imshow ("Faces found", image)

cv2.waitKey (0)

Finally, we display the model and wait for the user to press a key.

Python Tutorial for Computer Vision and Face Detection with OpenCV

Python Tutorial for Computer Vision and Face Detection with OpenCV

Python Tutorial for Computer Vision and Face Detection with OpenCV: Learn Vision Includes all OpenCV Image Processing Features with Simple Examples. Face Detection, Face Recognition

Computer Vision is an AI based, that is, Artificial Intelligence based technology that allows computers to understand and label images. Its now used in Convenience stores, Driver-less Car Testing, Security Access Mechanisms, Policing and Investigations Surveillance, Daily Medical Diagnosis monitoring health of crops and live stock and so on and so forth..

A common example will be face detection and unlocking mechanism that you use in your mobile phone. We use that daily. That is also a big application of Computer Vision. And today, top technology companies like Amazon, Google, Microsoft, Facebook etc are investing millions and millions of Dollars into Computer Vision based research and product development.

Computer vision allows us to analyze and leverage image and video data, with applications in a variety of industries, including self-driving cars, social network apps, medical diagnostics, and many more.

As the fastest growing language in popularity, Python is well suited to leverage the power of existing computer vision libraries to learn from all this image and video data.

In this course we'll teach you everything you need to know to become an expert in computer vision! This $20 billion dollar industry will be one of the most important job markets in the years to come.

What you'll learn

  • Use OpenCV to work with image files
  • Perform image manipulation with OpenCV, including smoothing, blurring, thresholding, and morphological operations.
  • Create Face Detection Software
  • Detect Objects, including corner, edge, and grid detection techniques with OpenCV and Python
  • Use Python and Deep Learning to build image classifiers
  • Use Python and OpenCV to draw shapes on images and videos
  • Create Color Histograms with OpenCV
  • Study from MIT notes and get Interview questions
  • Crack image processing limits by developing Applications.

Face Detection in Python using OpenCV with Haar Cascade Classifiers

Face Detection in Python using OpenCV with Haar Cascade Classifiers

In this tutorial, we will be building a simple Python script that deals with detecting human faces in an image, we will be using Haar Cascade Classifiers in OpenCV library.

Object detection is a computer technology related to computer vision and image processing that deals with detecting instances of semantic objects of a certain class ( such as human faces, cars, fruits, etc. ) in digital images and videos.

Haar feature-based cascade classifiers is a machine learning based approach where a cascade function is trained from a lot of positive and negative images. It is then used to detect objects in other images.

The nice thing about haar feature-based cascade classifiers is that you can make a classifier of any object you want, OpenCV already provided some classifier parameters to you, so you don't have to collect any data to train on it.

To get started, install the requirements:

pip3 install opencv-python

Alright, create a new Python file and follow along, let's first import OpenCV:

import cv2

You gonna need a sample image to test with, make sure it has clear front faces in it, I will use this stock image that contains two nice lovely kids:

# loading the test image
image = cv2.imread("kids.jpg")

The function imread() loads an image from the specified file and returns it as a numpy N-dimensional array.

Before we detect faces in the image, we will first need to convert the image to grayscale, that is because the function we gonna use to detect faces expects a grayscale image:

# converting to grayscale
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

The function cvtColor() converts an input image from one color space to another, we specified cv2.COLOR_BGR2GRAY code, which means converting from BGR ( Blue Green Red ) to grayscale.

Since this tutorial is about detecting human faces, go ahead and download the haar cascade for human face detection in this list. More precisely, "haarcascade_frontalface_default.xml". Let's put it in a folder called "cascades" (or whatever) and then load it:

# initialize the face recognizer (default face haar cascade)
face_cascade = cv2.CascadeClassifier("cascades/haarcascade_fontalface_default.xml")

Let's now detect all the faces in the image:

# detect all the faces in the image
faces = face_cascade.detectMultiScale(image_gray)
# print the number of faces detected
print(f"{len(faces)} faces detected in the image.")

detectMultiScale() function takes an image as parameter and detects objects of different sizes as a list of rectangles, let's draw these rectangles in the image:

# for every face, draw a blue rectangle
for x, y, width, height in faces:
    cv2.rectangle(image, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2)

Finally, let's save the new image:

# save the image with rectangles
cv2.imwrite("kids_detected.jpg", image)

Here is my resulting image:

Pretty cool, right? Feel free to use other object classifiers, other images and even more interesting, use your webcam ! Here is the code for that:

import cv2

# create a new cam object
cap = cv2.VideoCapture(0)

# initialize the face recognizer (default face haar cascade)
face_cascade = cv2.CascadeClassifier("cascades/haarcascade_fontalface_default.xml")

while True:
    # read the image from the cam
    _, image = cap.read()
    # converting to grayscale
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # detect all the faces in the image
    faces = face_cascade.detectMultiScale(image_gray, 1.3, 5)

    # for every face, draw a blue rectangle
    for x, y, width, height in faces:
        cv2.rectangle(image, (x, y), (x + width, y + height), color=(255, 0, 0), thickness=2)

    cv2.imshow("image", image)

    if cv2.waitKey(1) == ord("q"):
        break

cap.release()
cv2.destroyAllWindows()

Once you execute that ( if you have a webcam of course ), it will open up your webcam and start drawing blue rectangles around all front faces in the image. The code isn't that challenging, all I changed is, instead of reading the image from a file, I created a VideoCapture object that reads from it every time in a while loop, once you press the q button, the main loop will end.

Check the official OpenCV documentation for Face Detection.

Alright, this is it for this tutorial, you can get all tutorial materials ( including the testing image, the haar cascade, and the full code ) here.

Happy Coding ♥