How to Use OpenCV in Python to Detect Faces in Images

In this Python OpenCV article we are going to learn about How to Use OpenCV in Python to Detect Faces in Images, so OpenCV is an open source computer vision library that provides tools for image and video processing. it is mostly used in different types ofapplications such as object recognition, tracking and facial recognition. In this article we want to learn how to use OpenCV in Python to detect faces in images.

 

 

 

How to Use OpenCV in Python to Detect Faces in Images

First of all we need to install Python OpenCV

 

 

So now that we have installed Python OpenCV, let’s load and display an image using Python and OpenCV.

In the above code we have loaded our image using the cv2.imread()  function. this function takes path of the image as its argument and returns NumPy array representing the image. 

 

 

If you run the code you will see an image in the output

How to Use OpenCV in Python to Detect Faces in Images
How to Use OpenCV in Python to Detect Faces in Images

 

 

Now let’s learn about face detection using Python and OpenCV, for detecting faces in an image, we can use  pre trained Haar Cascade classifier. Haar Cascades are classifiers that use Haar like features to detect objects in an image. OpenCV comes with pre trained Haar Cascade classifier specifically for face detection. we can use this classifier to detect faces in our image, make sure that you have downloaded HaarCascade Classifier.

 

This is the complete code

 

 

So in the above code first we have loaded the image using the cv2.imread() function. after that we have converted the image to grayscale using the cv2.cvtColor() function. this is because the Haar Cascade classifier works better with grayscale images.

 

 

Next we have loaded pre trained Haar Cascade classifier using the cv2.CascadeClassifier() function. this function takes the path of the classifier file as its argument. haarcascade_frontalface_default.xml file is included with OpenCV, and also you can download that.

 

After that we use detectMultiScale() function of the Haar Cascade classifier to detect faces in the grayscale image. this function takes several parameters including image, scale factor, and minimum number of neighbors.

 

And at the end we loop over the detected faces and draw rectangles around them using the cv2.rectangle() function. and we display the image using the cv2.imshow() function.

 

 

 

If you run the code you will see that one face is detected in the image

How to Use OpenCV in Python to Detect Faces in Images
How to Use OpenCV in Python to Detect Faces in Images

 

 

 

Learn More on Python OpenCV

Leave a Comment