Detect number of faces from an image in Python using OpenCV

In this tutorial, We are going to learn an interesting thing which is how to detect the number of faces in an image using OpenCV in Python. This tutorial is a machine learning based approach where we use the cv2 module from the OpenCV library in the program. In order to learn this tutorial in an easy way, we have to understand what is OpenCV.

What is OpenCV in Python?

OpenCV is a library in Python which is used for image or video processing.

Some more OpenCV tutorials:

How to display or read an image using OpenCV in Python?

First of all, we have to learn how to show or display the image on the output page. so let’s start to understand step by step.

Python program:

import cv2
my=cv2.imread(r"C:\Users\BIPIN KUMAR\Desktop\machine learninng/bipin.jpg")
my2=cv2.imread(r"C:\Users\BIPIN KUMAR\Desktop\machine learninng/bipin.jpg",0)
cv2.imshow("bipin",my2)
cv2.waitKey(0)
cv2.destroyallWindows()

The term used in the above program is described below.

  • Here we include the cv2 module in our program by using import function.
  • The function imread use to read the original location of our jpg file.
  • To get the image in grayscale, here we are using the zero(0).
  • The term waitKey(0) used to hold the output screen untill the user press any key and destroyallWindows use to close output window and to come back on editor page.

Output:

Show image using OpenCV Python

Python program to find the number of faces in a given image

Let us assume that the picture provided by the user whose name is group1.

Detect faces using OpenCV in Python

A sample group photo to detect faces using OpenCV

Python program:

import cv2
my=cv2.imread(r"C:\Users\BIPIN KUMAR\Desktop\machine learninng/group1.jpg")
my2=cv2.imread(r"C:\Users\BIPIN KUMAR\Desktop\machine learninng/group1.jpg",0)
facedetector=cv2.CascadeClassifier(r"C:\Users\BIPIN KUMAR\Desktop\machine learninng\haarcascades\haarcascade_frontalface_default.xml")
face=facedetector.detectMultiScale(my2,1.1,5)
print('number of faces:')
print(len(face))
for x,y,z,h in face:
    cv2.rectangle(my,(x,y),(x+z,y+h),(0,0,225),3)
cv2.imshow("facedetective",my)
cv2.waitKey(0)
cv2.destroyallWindows()

Output:

number of faces:

4

Output figure:

detect number of faces in an image using OpenCV Python

Faces detected and counted

So Guy’s, I hope you understand how to detect and count number of faces from an image using OpenCV in Python. If you have any doubt feel free to leave a comment.

Leave a Reply

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