The Wayback Machine - https://web.archive.org/web/20241005233455/https://www.geeksforgeeks.org/python-eye-blink-detection-project/
Open In App

Python – Eye blink detection project

Last Updated : 30 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this tutorial you will learn about detecting a blink of human eye with the feature mappers knows as haar cascades. Here in the project, we will use the python language along with the OpenCV library for the algorithm execution and image processing respectively. The haar cascades we are going to use in the project are pretrained and stored along with the OpenCV library as haarcascade_frontalface_default.xml and haarcascade_eye_tree_eyeglasses.xml files. The project develops a basic understanding of the systems such as driver drowsiness detection, eye blink locks, eye detection, face detection and also the haar cascades usage with the OpenCV library.
About Haar Cascades: 
Haar feature-based cascade classifiers is an effective object detection method proposed by Paul Viola and Michael Jones in their paper, “Rapid Object Detection using a Boosted Cascade of Simple Features” in 2001. It is a machine learning-based approach where a cascade function is trained from a lot of positive and negative images. Here positive images are the samples which contain the target object and negative are the ones which don’t. It takes a lot of positive and negative samples to train the classifier.
 

Haar features , source – OpenCV docs

Now, we extract the features from the given input image with the haar features shown in the above image. They are just like convolutional kernels. Each feature is a single value obtained by subtracting the sum of pixels under the white rectangle from the sum of pixels under the black rectangle. 
 

Application of haarcascades, source – OpenCV Docs

The Excessive calculation: 
With all the possible sizes of the classifiers the features are calculated, but the amount of computation it takes to calculate the features, a 24×24 window results over 160000 features. Also for each feature calculation, the sum of the pixels is also needed. To make it computationally less expensive the creators of haar cascades introduced the integral image, which means however large your image, it reduces the calculations for a given pixel to an operation involving just four pixels.
The false features 
Now among the features that are calculated, most of the features are false and irrelevant. Now the window which is applied to a region of the image may see a different region which seems with the same features to the window but is not in reality. So, there is a need to remove the false features which were done by the AdaBoost which helped select the best features out of 160000+ features. Adaboost short form of Adaptive Boosting is a Machine learning algorithm which was used for this sole task.
Algorithm : 
 

The frame is captured and converted to grayscale.
Bilateral Filtering is applied to remove impurities.
Face is detected with the haarcascade.
The ROI (Region Of Image) of Face is fed to eye detection part of algorithm.
Eyes are detected and resulting list is passed to if-else construct.
If the length of list is more than two, means that the eyes are there.
Else the program is marked to be eye blinked and restarted.

Code: 
The haarcascade_frontalface_default.xml and haarcascade_eye_tree_eyeglasses.xml are the xml files stored in the same directory as the python script. 
 

Python3




#All the imports go here
import numpy as np
import cv2
 
#Initializing the face and eye cascade classifiers from xml files
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye_tree_eyeglasses.xml')
 
#Variable store execution state
first_read = True
 
#Starting the video capture
cap = cv2.VideoCapture(0)
ret,img = cap.read()
 
while(ret):
    ret,img = cap.read()
    #Converting the recorded image to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    #Applying filter to remove impurities
    gray = cv2.bilateralFilter(gray,5,1,1)
 
    #Detecting the face for region of image to be fed to eye classifier
    faces = face_cascade.detectMultiScale(gray, 1.3, 5,minSize=(200,200))
    if(len(faces)>0):
        for (x,y,w,h) in faces:
            img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
 
            #roi_face is face which is input to eye classifier
            roi_face = gray[y:y+h,x:x+w]
            roi_face_clr = img[y:y+h,x:x+w]
            eyes = eye_cascade.detectMultiScale(roi_face,1.3,5,minSize=(50,50))
 
            #Examining the length of eyes object for eyes
            if(len(eyes)>=2):
                #Check if program is running for detection
                if(first_read):
                    cv2.putText(img,
                    "Eye detected press s to begin",
                    (70,70), 
                    cv2.FONT_HERSHEY_PLAIN, 3,
                    (0,255,0),2)
                else:
                    cv2.putText(img,
                    "Eyes open!", (70,70),
                    cv2.FONT_HERSHEY_PLAIN, 2,
                    (255,255,255),2)
            else:
                if(first_read):
                    #To ensure if the eyes are present before starting
                    cv2.putText(img,
                    "No eyes detected", (70,70),
                    cv2.FONT_HERSHEY_PLAIN, 3,
                    (0,0,255),2)
                else:
                    #This will print on console and restart the algorithm
                    print("Blink detected--------------")
                    cv2.waitKey(3000)
                    first_read=True
             
    else:
        cv2.putText(img,
        "No face detected",(100,100),
        cv2.FONT_HERSHEY_PLAIN, 3,
        (0,255,0),2)
 
    #Controlling the algorithm with keys
    cv2.imshow('img',img)
    a = cv2.waitKey(1)
    if(a==ord('q')):
        break
    elif(a==ord('s') and first_read):
        #This will start the detection
        first_read = False
 
cap.release()
cv2.destroyAllWindows()


Sample Output: 
 

Sample run of above code

The Source code and the cascade classifiers can be found here. 
 



Previous Article
Next Article

Similar Reads

Project Idea | Third -Eye : Aid for Blind
Project Title: Third Eye - Aid For Blind. Introduction: This project aims to develop a complete portable aid(Raspberry Pi) for blind pedestrians and deal with problems in existing systems efficiently. The system designed will detect an object or obstacle using ultrasonic sensors and gives audio instructions for guidance. It also gives information a
2 min read
Project Idea | God's Eye
Project Idea: Complete user's Activities tracking with Remote Assistance This Program is divided into two major modules one is for complete activity tracking and can even tell which activity is currently active on the user's side. Can also work as a Global Keylogger to log the text written by a user on any process window ( Only when Proper undertak
3 min read
Object Detection with Detection Transformer (DETR) by Facebook
Facebook has just released its State of the art object detection Model on 27 May 2020. They are calling it DERT stands for Detection Transformer as it uses transformers to detect objects.This is the first time that transformer is used for such a task of Object detection along with a Convolutional Neural network. There are other Object detection mod
7 min read
Comparing anomaly detection algorithms for outlier detection on toy datasets in Scikit Learn
Anomaly is a deviation from the expected or normal behavior or pattern. Anomaly detection is the process of identifying these unusual patterns or behaviors in data. It is important because anomalies can indicate important events or problems, such as fraudulent activity, equipment failure, or security breaches. Anomaly detection is used in a variety
9 min read
Keeping the eye on Keras models with CodeMonitor
If you work with deep learning, you probably have faced a situation where your model takes too long to learn, and you have to keep watching its progress, however staying in front of the desk watching it learn is not exactly the most exciting thing ever, for this reason, this article's purpose is to introduce CodeMonitor, a simple but very useful py
4 min read
Eye Tracking Metrics - Machine Learning
Eye-tracking is an important and essential field researchers sought after. Eye-tracking is also an emerging field and has its benefits and is used in multiple ways. Fixation and Saccade are two basic components of eye movements used in Eye tracking. A saccade is the quick or immediate eye movement between fixations to move the eye-gaze from one poi
5 min read
Tensorflow.js tf.eye() Function
Tensorflow.js is an open-source library for creating machine learning models in Javascript that allows users to run the models directly in the browser. The tf.eye() is a function defined in the class tf.Tensor. It’s used to create an identity matrix of specified rows and columns. An identity matrix of shape [m, n] consists of value one at all diago
3 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
Project Idea (Augmented Reality - ARuco Code Detection and Estimation)
Project Idea : A project based on scanning and detecting Aruco codes. Implementing Homography for estimation of intrinsic and extrinsic camera calibration parameters and inclusion of Pose Estimation for the implementation of augmented Reality projects in further future projects. For Qr Code Detection Visit : this linkFor more Projects visit : Sahil
4 min read
Project Idea | Driver distraction and drowsiness detection system - DCube
Project Title: DCube Introduction:Car accident is the major cause of death in which around 1.3 million people die every year. Majority of these accidents are caused because of distraction or the drowsiness of driver. Construction of high-speed highway roads had diminished the margin of error for the driver. The countless number of people drives for
3 min read
Project Idea | Domain term detection and Hierarchical concept creation
Project Title: Domain term detection and Hierarchical concept creation Introduction: Domain Term Detection and Hierarchical Concept Creation in which given set of documents, main aims is to identify domain-specific term which mean that from given large set articles, tried to extract the domain for each article, and also created hierarchical represe
3 min read
Project Idea | Pavement distress detection using Drone Imaging
Project Title: Pavement Distress Detection Using Drone Imaging Introduction: Street pavement construction and repair includes a huge part of Indian metropolitan spending budgets. Survey and monitoring upkeep are crucial and important measures against pavement distress like both holes, blocked drains, etc. that can bring down the money related weigh
5 min read
Human Scream Detection and Analysis for Controlling Crime Rate - Project Idea
Project Title: Human Scream Detection and Analysis for Controlling Crime Rate using Machine Learning and Deep Learning Crime is the biggest social problem of our society which is spreading day by day. Thousands of crimes are committed every day, and still many are occurring right now also all over the world. A crime occurs in many faces, it can hap
6 min read
Project Idea | (Detection of Malicious Network activity)
Aim : As internet activities have incremented a lot now a days. The possibility of illegal access of private data is also increased. The aim of this project is to filter the network activities and to decide which are illegal of them. The process is similar to spam filtering from emails. Tool : This project is based on Machine learning algorithms wh
2 min read
Project Idea | (Robust Pedestrian detection)
The aim of this project is to develop an application which can detect pedestrians effectively. The problem of motion-based object detection can be divided into two parts: a) Classifying pedestrians and non pedestrians features a) Detecting pedestrians in each frame b) Associating the detections corresponding to the same object over time Tool :This
2 min read
Project Idea | Motion detection using Background Subtraction Techniques
Foreground detection based on video streams is the first step in computer vision applications, including real-time tracking and event analysis. Many researchers in the field of image and video semantics analysis pay attention to intelligent video surveillance in residential areas, junctions, shopping malls, subways, and airports which are closely a
4 min read
Project Idea - Object Detection and Tracking
Project title: Object Detection and Tracking Introduction: A lot of people go to supermarkets and retail stores and shops to idle around and window-shop instead of purchasing any products. The thought of analyzing this kind of behavior was intriguing. How does this kind of behavior affect product sales?What time periods these people were coming in?
5 min read
Project Idea | (Project Approval System)
Academic Project management is a major issue which is faced by many educational institutes, the main reason for this is there is no automated system followed in any institute. College management/staff gathers all the project reports and project sources from students and store them physically in some locations probably libraries. To overcome this pr
2 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
Car driving using hand detection in Python
In this project, we are going to demonstrate how one can drive a car by just detecting hand gestures on the steering wheel. Let's say the requirement is something like this - If driver wants to start the car then put both of your hands on the steering wheel. If someone having no hands on a steering wheel that means brakes of car will be applied slo
3 min read
Python | Smile detection using OpenCV
Emotion detectors are used in many industries, one being the media industry where it is important for the companies to determine the public reaction to their products. In this article, we are going to build a smile detector using OpenCV which takes in live feed from webcam. The smile/happiness detector that we are going to implement would be a raw
3 min read
Python | Haar Cascades for Object Detection
Object Detection is a computer technology related to computer vision, image processing and deep learning that deals with detecting instances of objects in images and videos. We will do object detection in this article using something known as haar cascades. What are Haar Cascades? Haar Cascade classifiers are an effective way for object detection.
2 min read
Gun Detection using Python-OpenCV
Gun Detection using Object Detection is a helpful tool to have in your repository. It forms the backbone of many fantastic industrial applications. We can use this project for real threat detection in companies or organizations. Prerequisites: Python OpenCV OpenCV(Open Source Computer Vision Library) is a highly optimized library with a focus on Re
4 min read
Tumor Detection using classification - Machine Learning and Python
In this article, we will be making a project through Python language which will be using some Machine Learning Algorithms too. It will be an exciting one as after this project you will understand the concepts of using AI & ML with a scripting language. The following libraries/packages will be used in this project: numpy: It's a Python library t
9 min read
Automating Scrolling using Python-Opencv by Color Detection
Prerequisites: OpencvPyAutoGUI It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own. App
2 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 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
Online Payment Fraud Detection using Machine Learning in Python
As we are approaching modernity, the trend of paying online is increasing tremendously. It is very beneficial for the buyer to pay online as it saves time, and solves the problem of free money. Also, we do not need to carry cash with us. But we all know that Good thing are accompanied by bad things. The online payment method leads to fraud that can
5 min read
Pneumonia Detection Using CNN in Python
In this article, we will learn how to build a classifier using a simple Convolution Neural Network which can classify the images of patient's xray to detect whether the patient is Normal or affected by Pneumonia. To get more understanding, follow the steps accordingly. Importing Libraries The libraries we will using are : Pandas- The pandas library
10 min read
Z score for Outlier Detection - Python
Z score is an important concept in statistics. Z score is also called standard score. This score helps to understand if a data value is greater or smaller than mean and how far away it is from the mean. More specifically, Z score tells how many standard deviations away a data point is from the mean. Z score = (x -mean) / std. deviationA normal dist
2 min read