As we move forward, there are new breakthroughs happening in the field of Machine Learning and Deep Learning every day, there are a lot of learners who want to get into this field and OpenCV is one of the most used, essential, and versatile python libraries available for anything and everything related to the images.
Let's start with installing the OpenCV. It is as straightforward as installing any other python library and you can pip install it but mind the name. For documentation and tutorial visit the offical page.
Once you’ve installed it, let us begin the tutorial. OpenCV alone is enough for this tutorial, we’ll not require any other library. Let’s import it first, read an image and display it.
The test image I have used is originally an RGB image of 190*380 pixels. So I have created a window of 200*400 to display the image. Feel free to play with this parameter.
To display an image through openCV, Although cv2.imread() is alone enough but last 3 lines are the standard practice for a better working of code.
Now that we’re able to read and display the image, it’s time to detect the face. For face detection, we’ll use the Haar feature-based cascade classifiers. This method was proposed by Paul Viola and Michael Jones in their research paper, “Rapid Object Detection using a Boosted Cascade of Simple Features” in 2001.
OpenCV provides a training method (see Cascade Classifier Training) or pre-trained models. The pre-trained models are located in the data folder in the OpenCV installation or can be found here. Simply download the XML files and place them in the data folder in the current working directory. we’ll use haarcascade_frontalface_alt.xml for this tutorial.
Once the face is detected then we need to draw a mark (in this case a rectangle) around it. The following function does both the task, it first detects the face and then helps us in marking them.
Now you can test your images on this for face detection. Try to tune the scaling_factor parameter for better results.
For the next steps, you can try to convert all the code into a function and run it with one call. or use the Argument parser to pass the parameters.
This tutorial was with static images, In the next tutorial, I’ll try to do the same with the help of a webcam or live images. If you like this tutorial then give some claps and follow me here and on LinkedIn.
Feel free to ask any related questions. Thank you all and take care.
For reference and additional reading:
- Test images are taken from the web