Coders Packet

Face Detection in live feed using openCV and Python

By Deepak Kumar Jha

Program detects the face in webcam and when we press key 's' from keyboard, it will save all the detected face in your system as desired location. I have used Python language and OpenCV library.

As command-line inputs, I first pass in the image using the webcam and cascade names. I'm going to use the live image as well as OpenCV's basic face detection cascade.

Now we'll build the cascade and connect it to our face cascade. This saves the face cascade to memory and makes it available for usage. Remember that the cascade is nothing more than an XML file containing the data needed to detect faces. We read the image and convert it to grayscale in this step. In OpenCV, many operations are done in grayscale.


The detectMultiScale method is a generic object detection function. It detects the face cascade because that's what we're calling it.The first one is for grayscale image.

The scaleFactor is the second. Because some faces are closer to the camera, they appear larger than those in the background. This is compensated for by the scaling factor.

To detect objects, the detection method employs a moving window. min Before declaring the face identified, Neighbors determines how many items are detected around the present one. min Size, on the other hand, specifies the size of each window.

Below, we can see how the face cascade is connected and detect face using detectMultiScale() function, also we are drawing a rectangle around the detected face using the coordinates returned by cascade.


    faces= facecascade.detectMultiScale(img,1.1,2)

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

        area= w*h

        if area>500:




Now, we will see, how the program works basically

When we run our program, a window will open having name 'webcam' and it will capture live images using the webcam. As you can see below, how i am using my webcam to show my laptop screen.



As soon as I focus my webcam on image containing faces, it starts detecting all the faces in image as you can see below, it has detected all the faces in the images.


Now, to save all the detected faces to our system, we just need to press key 's' from keyboard in real time and as soon as we press the key, a pop up will appear showing "image saved" and detected face has been saved to our system. And at any time if we need to close the program and webcam we just need to press 'q' key from keyboard.


Now, you can see the detected face saved in my system at the location I have provided in jpg format.



Download Complete Code


No comments yet