How can you easily detect a face using OpenCV

Original article was published on Deep Learning on Medium

Let’s move on to the code section…

First step will always be importing the necessary libraries, so when you’re working with Computer Vision there will be only three libraries that need to be imported.

Most important point is that if you’re working on Jupyter notebook or Google colaboratory or any other platforms like that, then you need to run the whole code in one cell only because we are not using plt.imshow(), instead of this we’re using cv2.imshow() which will cause the session crash, and the code will not give the output after that. Personally I will prefer sublime text or something like that.

Importing libraries will be like that

As I told you earlier we will not be using matplotlib here.

Next step will be adding the haar cascade for the detection, they are easily available on the internet.

We will load the haar cascade in a variable for example, face_cascade, now this is done by the class of cv2 which is CascadeClassifier.

Next this is to make a function face_detect() which take only one argument which is the image/video itself, in this function we use class of CascadeClassifier which is detectMultiScale which return the values of x and y coordinates of the point where the face is detected and it’s width and height, after that using these coordinates we draw the rectangle on the face.

Here, scaleFactor and minNeighbors are the arguments which help us to improve the accuracy of the detection.

Next step will be to open the webcam for the video capture

Here the ‘0’ indicates that we are using the inbuilt camera present in the laptop.

Now, let’s visualize the results

Here, k == 27 means the video window will close only when the ESC key is pressed.

Last step will be to release the camera and destroy all the windows after the work is done. This step is important as we are using cv2.imshow().

When we run the whole code in one go then we can see a white rectangle floating on the video only on the face part.

Hope it helps. Have a great day ahead.