Real time face detection in webcam using Python 3 will show you how your working webcam detects your face and draws a rectangle around your face. In my previous tutorial we have seen how you see yourself in webcam using Python. The same tutorial we will use here to detect your face and draw a rectangle around it to indicated your face. Make sure you do have the camera installed in your system in order to see yourself in webcam. Here in this example we will use OpenCv to capture the video and display into a frame. When you wish to close the video window you need to press ‘q’ from your keyboard.

Prerequisites

Have Python installed in Windows (or Unix)
Pyhton version and Packages
Here I am using Python 3.6.6 version
OpenCv version 3.4.2

You need an XML file for detecting face – haarcascade_frontalface_alt.xml. To download the file please go to the URL https://opencv.org/releases.html

Preparing your workspace

Preparing your workspace is one of the first things that you can do to make sure that you start off well. The first step is to check your working directory.

When you are working in the Python terminal, you need first navigate to the directory, where your file is located and then start up Python, i.e., you have to make sure that your file is located in the directory where you want to work from.

In the below image you see I have opened a cmd prompt and navigated to the directory where I have to create Python script for implementing the example “real time face detection in webcam using Python 3”.

python

Example Implementation

Now we will create the Python script and see how to implement real time face detection in webcam using Python 3.

In the below Python script we first import the required module OpenCv called cv2. Then we grab the reference to the webcam. Note that here I am using Laptop’s built-in webcam. Make sure your webcam works fine.

Notice we create the cascade and initialize it with our face cascade. This loads the face cascade into memory so it’s ready for use. Remember, the cascade is just an XML file that contains the data to detect faces.

To initialize you must download these XML file from the given link above. Once you download the zip file, extract and look for the desired files into opencv-3.4.2\data\haarcascades directory and copy the XML file under the C:\py_scripts where you have created below python script face_detection.py.

If you do not copy that XML file into the desired directory then you may get below error while you try to execute the below python script:

faces = faceCascade.detectMultiScale(frame)
cv2.error: OpenCV(3.4.2) \opencv\modules\objdetect\src\cascadedetect.cpp:1698: error: (-215:Assertion failed) !empty() in function ‘cv::CascadeClassifier::detectMultiScale’

Then we grab the reference to the webcam. Next we read frame by frame the video captures.

The detectMultiScale function is a general function that detects objects. Since we are calling it on the face cascade, that’s what it detects.

The function returns a list of rectangles in which it believes it found a face. Next, we will loop over where it thinks it found something.

This function returns 4 values: the x and y location of the rectangle, and the rectangle’s width and height (w , h).

We use these values to draw a rectangle using the built-in rectangle() function.

Finally we show it in frame. When you press “q” from keyboard, frame will disappears.

import cv2

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')

# grab the reference to the webcam
vs = cv2.VideoCapture(0)

# keep looping
while True:
	# grab the current frame
	ret, frame = vs.read()
  
	# if we are viewing a video and we did not grab a frame,
	# then we have reached the end of the video
	if frame is None:
		break
		
	faces = faceCascade.detectMultiScale(frame)

	for (x, y, w, h) in faces:
		cv2.rectangle(frame, (x, y), (x+w, y+h), (255,0,0), 2)
	
	# show the frame to our screen
	cv2.imshow("Video", frame)
	key = cv2.waitKey(1) & 0xFF

	# if the 'q' key is pressed, stop the loop
	if key == ord("q"):
		break
 
# close all windows
cv2.destroyAllWindows()

Testing the application

Now it’s time to test our application by executing the following command in the cmd prompt:

C:\py_scripts>python <python script name>.py

Once the script gets executed successfully, you will be able to see yourself in the frame and a rectangle is drawn around your face as shown in below image.

real time face detection in webcame using python

To exit you should press q from your keyboard.

That’s all. Hope you got idea on real time face detection in webcam using Python 3.

You may be interested to read see yourself in webcam using Python

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

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