The Wayback Machine - https://web.archive.org/web/20241001184659/https://www.geeksforgeeks.org/determine-the-face-tilt-using-opencv-python/
Open In App

Determine The Face Tilt Using OpenCV – Python

Last Updated : 03 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Requirements:

Algorithm:

  • 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 (x_{1}, y_{1})       & (x_{2},y_{2})      , the angle \theta       which the line joining the two points makes with the x-axis can be obtained from geometry using the following expression:

\theta = \arctan(\frac{x_2 - x_1}{y_2 - y_1})

  • 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:

Python

import cv2 as cv
import numpy as np
  
  
# 0 for webcam feed ; add "path to file"
# for detection in video file
capture = cv.VideoCapture(0)
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv.CascadeClassifier("haarcascade_eye.xml")
  
while True:
    ret, frame = capture.read()
    gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 5)
    x, y, w, h = 0, 0, 0, 0
    for (x, y, w, h) in faces:
        cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv.circle(frame, (x + int(w * 0.5), y +
                          int(h * 0.5)), 4, (0, 255, 0), -1)
    eyes = eye_cascade.detectMultiScale(gray[y:(y + h), x:(x + w)], 1.1, 4)
    index = 0
    eye_1 = [None, None, None, None]
    eye_2 = [None, None, None, None]
    for (ex, ey, ew, eh) in eyes:
        if index == 0:
            eye_1 = [ex, ey, ew, eh]
        elif index == 1:
            eye_2 = [ex, ey, ew, eh]
        cv.rectangle(frame[y:(y + h), x:(x + w)], (ex, ey),
                     (ex + ew, ey + eh), (0, 0, 255), 2)
        index = index + 1
    if (eye_1[0] is not None) and (eye_2[0] is not None):
        if eye_1[0] < eye_2[0]:
            left_eye = eye_1
            right_eye = eye_2
        else:
            left_eye = eye_2
            right_eye = eye_1
        left_eye_center = (
            int(left_eye[0] + (left_eye[2] / 2)), 
          int(left_eye[1] + (left_eye[3] / 2)))
          
        right_eye_center = (
            int(right_eye[0] + (right_eye[2] / 2)),
          int(right_eye[1] + (right_eye[3] / 2)))
          
        left_eye_x = left_eye_center[0]
        left_eye_y = left_eye_center[1]
        right_eye_x = right_eye_center[0]
        right_eye_y = right_eye_center[1]
  
        delta_x = right_eye_x - left_eye_x
        delta_y = right_eye_y - left_eye_y
          
        # Slope of line formula
        angle = np.arctan(delta_y / delta_x)  
          
        # Converting radians to degrees
        angle = (angle * 180) / np.pi  
  
        # 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)
        if angle > 10:
            cv.putText(frame, 'RIGHT TILT :' + str(int(angle))+' degrees',
                       (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1,
                       (0, 0, 0), 2, cv.LINE_4)
        elif angle < -10:
            cv.putText(frame, 'LEFT TILT :' + str(int(angle))+' degrees',
                       (20, 30), cv.FONT_HERSHEY_SIMPLEX, 1, 
                       (0, 0, 0), 2, cv.LINE_4)
        else:
            cv.putText(frame, 'STRAIGHT :', (20, 30),
                       cv.FONT_HERSHEY_SIMPLEX, 1, 
                       (0, 0, 0), 2, cv.LINE_4)
  
    cv.imshow('Frame', frame)
  
    if cv.waitKey(1) & 0xFF == 27:
        break
capture.release()
cv.destroyAllWindows()

                    

Output:



Previous Article
Next Article

Similar Reads

OpenCV - Facial Landmarks and Face Detection using dlib and OpenCV
Content has been removed on Author's request.
1 min read
Face detection using Cascade Classifier using OpenCV-Python
In this article, we are going to see how to detect faces using a cascade classifier in OpenCV Python. Face detection has much significance in different fields of today's world. It is a significant step in several applications, face recognition (also used as biometrics), photography (for auto-focus on the face), face analysis (age, gender, emotion r
4 min read
Face Detection using Python and OpenCV with webcam
OpenCV is a Library which is used to carry out image processing using programming languages like python. This project utilizes OpenCV Library to make a Real-Time Face Detection using your webcam as a primary camera.Following are the requirements for it:- Python 2.7OpenCVNumpyHaar Cascade Frontal face classifiers Approach/Algorithms used: This proje
4 min read
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV
In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign la
4 min read
turtle.tilt() function in Python
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.tilt() This function is used to rotate the turtleshape by the angle from its current tilt-angle, but do NOT change the turtle'
1 min read
Face Alignment with OpenCV and Python
Face Alignment is the technique in which the image of the person is rotated according to the angle of the eyes. This technique is actually used as a part of the pipeline process in which facial detection is done using the image. This implementation of face alignment can be easily done with the help of python module cv2(computer vision). It has so m
6 min read
Opencv Python program for Face Detection
The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects. Here is the steps to download th
2 min read
Face Recognition with Local Binary Patterns (LBPs) and OpenCV
In this article, Face Recognition with Local Binary Patterns (LBPs) and OpenCV is discussed. Let's start with understanding the logic behind performing face recognition using LBPs. A beginner-friendly explanation of LBPs is described below. Local Binary Patterns (LBP)LBP stands for Local Binary Patterns. It's a technique used to describe the textur
13 min read
Transition from OpenCV 2 to OpenCV 3.x
OpenCV is one of the most popular and most used Computer vision libraries. It contains tools to carry out image and video processing. When OpenCV 3..4.1 is an improved version of OpenCV 2.4 as it introduced new algorithms and features. Although some of the existing modules were rewritten and moved to sub-modules. In this articles, I will focus on t
2 min read
Top Books for Learning OpenCV: Computer Vision with OpenCV Library
OpenCV or Open Source Computer Vision Library, is an open-source computer vision and machine learning software library. It's extensively used for real-time computer vision tasks such as object detection, face recognition, image processing, etc. Whether you're a beginner or an experienced developer looking to deepen your understanding of OpenCV, her
5 min read
Python | Multiple Face Recognition using dlib
This article aims to quickly build a Python face recognition program to easily train multiple images per person and get started with recognizing known faces in an image. In this article, the code uses ageitgey's face_recognition API for Python. This API is built using dlib's face recognition algorithms and it allows the user to easily implement fac
4 min read
Draw smiling face emoji using Turtle in Python
Prerequisite: Python Turtle Basics Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc. In this article, we will see how to draw a smiling face emoji using the Turtl
2 min read
Draw a happy face using Arcade Library in Python
Arcade is a Python module used for developing 2D games. For drawing a happy face, steps are as follows: Import arcade library.import arcade Open the window.arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) The function used with arcade is open_window. This command opens a window with a given size i.e width and height along with screen t
3 min read
How to create a Face Detection Android App using Machine Learning KIT on Firebase
Pre-requisites: Firebase Machine Learning kitAdding Firebase to Android AppFirebase ML KIT aims to make machine learning more accessible, by providing a range of pre-trained models that can use in the iOS and Android apps. Let's use ML Kit’s Face Detection API which will identify faces in photos. By the end of this article, we’ll have an app that c
9 min read
Python - Face detection and sending notification
Nowadays python has become one of the most popular languages as well as favorite programming language among developers. The simplified syntax and pattern of this language make the presence of this language in the trending list. The biggest strength of Python is a huge collection of standard library which can be used for the following: Machine Learn
4 min read
Face Mask detection and Thermal scanner for Covid care - Python Project
IntroductionThe coronavirus COVID-19 pandemic is triggering a worldwide health catastrophe, hence the World Health Organization recommends wearing a face mask in designated areas. Face Mask Detection and Hand Sanitization have been a well-known subject in recent times, as well as in image preparation and computer vision. Many new computations are b
5 min read
Determine the type of an image in Python using imghdr
Suppose you are given an image type file and you need to determine the type of that file. In simple words, you need to get the extension of that image type file. This can be used in a project to verify whether the image you have requested for is actually an image and with which extension does it come. imghdr module Use following command for Install
2 min read
Determine a CRS is Projected or Not Using Python OSMnx projection Module
The coordinate reference system (CRS) is a framework that measures locations on the earth's surface as coordinates. Geographic Coordinate Reference System uses latitude and longitude to specify a location on Earth (unit in degrees). On the other hand, the Projected Coordinate System employs a two-dimensional XY plane using northing (Y) and easting
2 min read
Installing Face-unlock on Ubuntu
"Facerec - Linux face unlock" is a highly optimized face authentication system for Ubuntu Linux that works while logging in, running "sudo" commands, etc. and it has a user-friendly CLI to operate it. GitHub Link: https://github.com/rushabh-v/linux_face_unlock Installation 1. Update Sources This command will get all the updates from the source repo
2 min read
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
Image resizing using Seam carving using OpenCV in Python
Seam carving is an effective image processing technique with the help of which an image can be resized without removing important elements from the image. The basic approach is to find all the continuous pixels with low energy from left to right or from top to bottom. After the region is selected, it is removed from the original image, leaving only
2 min read
Step-by-Step Guide to Using RANSAC in OpenCV using Python
RANSAC (Random Sample Consensus) is an iterative method to estimate the parameters of a mathematical model from a set of observed data that contains outliers. In computer vision, it's often used for tasks like estimating the fundamental matrix, homography, or any fitting problem with noisy data. In Python, OpenCV provides built-in support for RANSA
4 min read
Power Method - Determine Largest Eigenvalue and Eigenvector in Python
The power method is an iterative algorithm that can be used to determine the largest eigenvalue of a square matrix. The algorithm works by starting with a random initial vector, and then iteratively applying the matrix to the vector and normalizing the result to obtain a sequence of improved approximations for the eigenvector associated with the la
6 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Python | Play a video in reverse mode using OpenCV
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV's application areas include : 1) Facial recognition system 2) motion tracking 3) Artificial neural network 4) Deep neural network 5) video streaming etc. In Python, one can use an OpenCV library named C
3 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Opening multiple color windows to capture using OpenCV in Python
OpenCV is an open source computer vision library that works with many programming languages and provides a vast scope to understand the subject of computer vision.In this example we will use OpenCV to open the camera of the system and capture the video in two different colors. Approach: With the libraries available in OpenCV-Python below we will op
2 min read
Converting Color video to grayscale using OpenCV in Python
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will see how to convert a colored video to a gray-scale format. Approach: Import the cv2 module.Read the video file to be converted usi
1 min read
Practice Tags :