Determine The Face Tilt Using OpenCV – Python
In this article, we are going to see how to determine the face tilt using OpenCV in Python.
To achieve this we will be using a popular computer vision library opencv-python. In this program with the help of the OpenCV library, we will detect faces in a live stream from a webcam or a video file and subsequently also determine the angle by how much the face is tilted.
- Install OpenCV for python.
- We will be using two pre-trained XML classifiers to detect faces and eyes respectively. These classifiers can be downloaded from opencv library or just click the links below.
- Classifier for face detection: haarcascade_frontalface_default.xml
- Classifier for eye detection: haarcascade_eye.xml
- First, we detect the face in the webcam feed/video using the above-mentioned haarcascade classifier for the face and make a green color bounding box around it.
- Next, we detect the eyes using a similar haarcascade classifier trained on eyes and make a red color bounding box around each eye.
- In addition to making a box around each eye, we also identify and store the center of each box. Here, we are assuming that the center of the bounding box is the same as the center of the eye.
- For computing the angle of tilt we will assume that the line joining the centers of two eyes is perpendicular to the face.
- We have the coordinates of two centers in terms of (x,y) coordinates. The x-axis is the horizontal axis and y-axis is the vertical axis.
- When two points are given & , the angle which the line joining the two points makes with the x-axis can be obtained from geometry using the following expression:
- In our case, the angle made by the line joining the centers of two eyes with the horizontal is computed. The positive angle indicates the right tilt and the negative angle indicates the left tilt.
- Provided a margin of error of 10 degrees (i.e, if the face tilts more than 10 degrees on either side the program will classify as right or left tilt).
Below is the implementation: