Category: publications

  • libmpface: MediaPipe head pose and eye tracking on Windows in C++

    mediapipe_head_windows
    Author
    Blaž Kovačič, M.Sc.
    Obstino – Assistive Technology Development Association

    Date
    September 2026

    Abstract

    In this paper we describe a practical approach of obtaining 3D facial landmarks, head pose estimation and eye tracking in Windows OS using C++.

    For this purpose we’ve developed a simple library called libmpface. As the name suggest, it is based on the MediaPipe framework, specifically it is based on the corresponding tflite model for obtaining facial landmarks.

    The library is very easy to use and is based on OpenCV and TensorFlow lite (specifically we use ValYouW/tflite-dist from github).

    The library was developed as a part of Obstino – Assistive Technology Association.

    As the library is improved, it is aimed at providing utility functions for programmers who want to develop accessibility and other useful applications.

    Library open-source code can be found on the link below: https://github.com/obstino-org/libmpface

    Introduction

    Assistive techonology (AT) and accessibility is a field that eventually helps improve the quality of life for persons with disabilities.

    There are many AT solutions that can help people. Some solutions may utilize physical switches to help people more easily control their device, eye tracking devices, gyroscopic mice. Additionally, the technology of artificial intelligence enables programmers to develop solutions that can track head movement or eye movement using the device camera. One example of this is the SmyleMouse, which tracks head movement and detects the smile facial gesture to enable Windows users to move the cursor and perform mouse click. Another similar solution is our Face Control Android application that detects facial movement to control the device.

    Many web camera based solutions using frontal face image rely on AI models that can accurately detect important key points on the face. These points are known as facial landmarks (see example image below for the MediaPipe facial landmarks)


    Figure 1: Facial landmark points for the MediaPipe head landmarks model (see here for full sized image).

    We recognized that for facial landmark detection in C++, a common approach is with use of the dlib facial landmark detector. Dlib is straightforward to set up, however their landmark detector does not accurately predict landmark points for larger rotations of the head. Additionally, their solution doesn’t predict landmarks very well for facial occlusions. The dlib facial landmark model is also relatively large, consuming about 100MB of hard drive space.

    With the development of AI head pose estimation neural network models, alternative approaches become possible. One such approach is by utilizing well-known MediaPipe landmark detection AI models released by Google.
    The benefits of using MediaPipe facial landmark detection model are computational efficiency, on-device support, public availability and documentation of their corresponding TensorFlow lite models. Finally, it enables accurate prediction 3D landmark points, which include eye gaze landmark points.

    Setting up the development environment

    The development environment is relatively easy to set up on the Windows operating system using Visual Studio.

    The environment in our work consists of:

    • C++ development: Microsort Visual Studio Community 2022
    • Computer vision library: OpenCV 3.4.18
    • TensorFlow library: tflite-dist v2.2.0
    • MediaPipe facial landmarks model: MediaPipe FaceLandmarker
    • HAAR cascade head detection files: *“opencv3410_frontalface_default.xml”*

    OpenCV was compiled manually using CMake GUI.

    The library tflite-dist is already precompiled for Windows and contains the necessary .lib and .dll and include files for quick setup.

    In URL provided above for the facial landmarks model, one can download the .task file, which is essentially a zip archieve that, when unzipped, amongst others contains the “face_landmarks_detector.tflite” tensorflow lite AI model. We use this model in our work.

    Our approach

    We created a single header library libmpface that can be used in the following way:

    • to obtain 468 3-dimensional facial landmark points (easy to convert to 2d)
    • compute normalized eye pupil position estimate (a number between -1.0 and +1.0)
    • obtain experimental head pose (roll, yaw, pitch angles in degrees)

    For this purpose, we have a header named libmpface.h with the class FaceLandmarkDetector.
    Some useful class methods are the following:

    • simple constructor FaceLandmarkDetector()
    • landmark detection accepting webcam opencv color image frame vector<cv::Point3f> detectLandmarks(cv::Mat& frame)
    • roll angle computation with float computeRoll(vector<cv::Point3f> landmarks, bool degrees = true)
    • yaw angle computation with float computeYaw(vector<cv::Point3f> landmarks, bool degrees = true)
    • pitch angle computation with float computePitch(vector<cv::Point3f> landmarks, bool degrees = true)
    • normalized eye position computation with cv::Point2f computeEyePosition(vector<cv::Point3f> landmarks, float outScaleX = 1.0f, float outScaleY = 1.0f)

    There is also the following low-level method pair<vector<cv::Point3f>, float> forward(cv::Mat imgFace). This method is used internally by detectLandmarks.

    Example usage of our library:

    Here we show a simple example use of our library which computes and draws facial landmark points using camera image.
    The example also computes roll, yaw and pitch angle approximates in degrees. It also uses eye position to display on app window whether the user is looking left or right (see figure below).


    Figure 2: Demonstration of our libmpface example application.

    C++ code for the example

    #include "libmpface.h"
    
    int main()
    {
        cv::Mat frame;
        cv::VideoCapture cap(0, cv::CAP_DSHOW);
        FaceLandmarkDetector landmarkDetector;
        
        if (!cap.isOpened()) {
            cout << "error opening\n";
            return -1;
        }
    
        cout << "opened\n";
    
        while(true)
        {
            cap.read(frame);
            cv::flip(frame, frame, 1);
    
            if (frame.empty()) {
                cout << "frame empty" << endl;
                std::this_thread::sleep_for(100ms);
                continue;
            }
    
            auto pts = landmarkDetector.detectLandmarks(frame);
            if (!pts.empty()) {
                auto pts2f = landmarkDetector.vectTo2f(pts);
                for (int i = 0; i < pts2f.size(); i++)
                    cv::circle(frame, pts2f[i], 1, cv::Scalar(0.0f, 255.0f, 0.0f), 1);
    
                float roll = landmarkDetector.computeRoll(pts);
                float yaw = landmarkDetector.computeYaw(pts);
                float pitch = landmarkDetector.computePitch(pts);
    
                cv::Point2f eyePos = landmarkDetector.computeEyePosition(pts, 1.0f, 1.0f);
                float xBias = -0.15f;
                eyePos.x -= xBias;
    
                string strRoll = std::format("roll: {:.2f} deg", roll);
                string strYaw = std::format("yaw: {:.2f} deg", yaw);
                string strPitch = std::format("pitch: {:.2f} deg", pitch);
                string strEyeX = std::format("eyeX: {:.2f}", eyePos.x);
                string strEyeY = std::format("eyeY: {:.2f}", eyePos.y);
    
                string strLR = "";
                if (eyePos.x <= -0.15f)
                    strLR = "looking left";
                else if (eyePos.x >= 0.15f)
                    strLR = "looking right";
    
                if (cv::waitKey(30) == 32)
                    std::this_thread::sleep_for(3000ms);
    
                int yPos = 10;
                for (string s : vector<string>{ strRoll, strYaw, strPitch, strEyeX, strEyeY, "", strLR })
                    cv::putText(frame, s, cv::Point(10, (yPos+=30)), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(50.0f, 150.0f, 50.0f), 2);
    
            }
    
            cv::imshow("libmpface test", frame);
    
            if (cv::waitKey(30) == 27)
                break;
        }
    
        return 0;
    }

    Algorithm description

    detectLandmarks class method

    Below, we write the simplified pseudocode for the high-level libmpface class method detectLandmarks

    public faceRegion = {}
    
    detectLandmarks(frame) {
        if(faceRegion.empty()) {
            faceRect = haarDetectFace(frame)
            if(!faceRect)
                return {};
            // expand rect height (above and below)-> total=150%
            faceRect2 = expandRectHeight(faceRect, 150%)
            faceRegion = faceRect2
        }
    
        if(faceRegion.empty())
            return {}
        
        imgFace1 = copyImageRect(frame, faceRegion)
        imgFace2 = resizeImage(imgFace1, Size(256, 256))
    
        {landmarks, score} = forward(imgFace2)
        if(score < 0.95) {
            faceRegion = {}
            return {}
        }
    
        // scale points from [0,256]x[0,256]
        // to [0,face1Width]x[0,face1Height]
        landmarks = scale(landmarks)
        // construct new faceRegion rect
        topLeft = findTopLeftPoint(landmarks)
        bottomRight = findBottomRightPoint(landmarks)
        faceRegion = Rect2f(topLeft, bottomRight);
        
        return landmarks;
    }

    computeRoll method

    Head roll angle describes how much head is tilted sideways left or sideways right.

    Roll computation in libmpface is done using computeRoll. The method first computes a centroid of 3D landmark points (obtained through detectLandmarks) as follows: \[ c = \frac{1}{N} \sum_{i=0}^{N}{\text{landmark}(i)} \]

    Roll angle \(\alpha\) is computed using \(c\) and three other landmark points using the following formula:

    \[\alpha = \frac{1}{3}\sum_{i\in \{8, 9, 151\}}\text{atan2}\left(v_y(i), v_x(i)\right)\] where \[v(i) = \text{landmark}(i)-c\]

    Here atan2 is a two argument inverse arc function. We divide by 3 to obtain average of atan of three points. The landmark points 8, 9, and 151 correspond to a vertical line on head, as shown in figure below.


    Figure 3: Select landmark points and centroid c used to compute roll angle approximation.

    computeYaw method

    Yaw angle \(\beta\) is computed similarly using \(c\) and six other landmark points on the nosetip using the following formula:

    \[\beta = \frac{\pi}{2} + \frac{1}{6} \times \sum_{i\in \{5, 4, 51, 281, 45, 275\}}\text{atan}\left(\frac{v_z(i)}{v_x(i)}\right)\] where \[v(i) = \text{landmark}(i)-c\]

    Here, in atan function we use the \(z\) component (depth) and horizontal \(x\) (as in image plane) component of \(v(i)\). Points 5, 4, 51, 281, 45, and 275 correspond to landmarks that are nearby around the nosetip (green in figure below).


    Figure 4: Select landmark points and centroid c used to compute yaw angle approximation.

    computePitch method

    Pitch angle \(\gamma\) is computed using \(c\) and six other landmark points on the nosetip using the following formula:

    \[\gamma = \frac{1}{6} \times \sum_{i\in \{5, 4, 51, 281, 45, 275\}}\text{atan}\left(\frac{v_y(i)}{v_z(i)}\right)\] where \[v(i) = \text{landmark}(i)-c\]

    Here, in atan function we use the \(z\) component (depth) and vertical \(y\) (as in image plane) component of \(v(i)\). Again, points 5, 4, 51, 281, 45, and 275 correspond to landmarks that are nearby around the nosetip (green in figure below).


    Figure 5: Select landmark points and centroid c used to compute pitch angle approximation.

    computeEyePosition method

    Mathematics behind eye position calculation (\(x_{eye}\) and \(y_{eye}\)) is shown below (optionally in code there are also scale factors for output values of x and y).

    First, we define:

    \(E = \text{landmark}(eyeIndex)\)

    \(L = \text{landmark}(eyeLeftCornerIndex)\)

    \(R = \text{landmark}(eyeRightCornerIndex)\)

    \(T = \text{landmark}(eyeTopIndex)\)

    \(B = \text{landmark}(eyeBottomIndex)\)

    Note that only \(x\) and \(y\) image plane landmark components are used in vectors \(E\), \(L\), \(R\), \(T\) and \(B\) above.

    Next, for horizontal eye position we have:

    \[u_1 = \frac{R – L}{||{R – L}||}\]

    \[v_1 = E-L\]

    \[x_{eye} = \frac{u_1 \cdot v_1 }{||R – L||}\]

    \[x_{eyeNorm} = 2(x_{eye} – 0.5)\]


    Figure 6: Left eye with vectors sketched for visual demonstration of horizontal eye position calculation.

    As we can see in figure above, \(u_1 \cdot v_1\) is basically a horizontal projection of eye position \(E\) on the line between points \(L\) and \(R\). What \(x_{eyeNorm}\) results in is a normalized value for eye position, giving values between -1 and +1. In practice, however, the normalized position values may reach values of about 0.5 at eye at left and right boundary, since the pupil \(E\) is surrounded by the iris, which adds some space at the boundary positions.

    Similarily, for the vertical eye position we have

    \[u_2 = \frac{T – B}{||{T – B}||}\]

    \[v_2 = E-B\]

    \[y_{eye} = \frac{u_2 \cdot v_2 }{||T – B||}\]

    \[y_{eyeNorm} = 2(y_{eye} – 0.5)\]


    Figure 6: Left eye with vectors sketched for visual demonstration of vertical eye position calculation.

    The mathematics is exactly the same as for horizontal eye position, except that different points are used in computation. The points used can be seen in figure above.

    Conclusion

    Here we presented our libmpface open source library. Our library’s main code is in a single header, written in Visual Studio C++. It is based on MediaPipe facial landmark detection models. It is simple to use, and enables accurate real-time acquisition of 468 3-dimensional facial landmark points.

    These points can be passed to libmpface auxiliary methods to find approximate 3D head rotation angles – roll, yaw and pitch. Additionally, the library enables experimental support for eye position tracking, giving normalized output values.

    The future work can include improvement and further testing of mentioned auxiliary methods, and use of this library in applicative assistive technology solutions.

  • On detecting facial gestures with code on Android

    publication_fc_gesture
    Author
    Blaž Kovačič, M.Sc.
    Obstino – Assistive Technology Development Association

    Date
    June 2026

    Introduction

    As a part of Obstino – Assistive Technology Development association, we’ve developed an algorithm that detects facial gestures, such as smile, eyebrow raise and mouth open. This algorithm is the subject of this article and will be presented in detail.

    The algorithm is a part of our free and open source Android app Face Control (see code on github)

    Our Face Control app (as available on the Google Play) is an assistive technology app to help disabled users control their Android devices using only movements of their face, eye gaze left/right and eye wink.

    App is demonstrated below:


    Our approach is written in Java code, and is outlined with the following steps: 1. Repeat-capture camera images using our CameraCapture.java class 2. Pass image to FaceDetector class from Android ML Kit’s Face Detection API to obtain the (x, y) image coordinates around special areas of the face, such as around the eyebrows – these are commonly known as facial landmarks 3. MAIN COMPONENT: Pass facial landmark points to our GestureRecognizer.java algorithms to detect changes in facial movements such as eyebrow raise and a smile

    In this publication, we first explain our approach in detail for the smile detection algorithm. There we present also the necessary theoretical background and pratical considerations and put them into context of smile detection algorithm. We also present and outline the eyebrow raise detection and detection of mouth open facial gestures. Finally, we conclude by summarizing our work.

    Rationale and advantages of our approach

    Facial gesture detection is a very applicable area, especially in the field of assistive technology. This is so because many disabled persons, such as people with quadriplegia, only have ability to move their face/head and very limited or no ability to move the rest of their body.

    The algorithm to detect, say, eyebrow raise or a smile, should be sensitive enough to detect small changes in expression – as opposed to detecting “absolute eyebrow position”. This is so because different people may have varying levels of expression of that facial gesture as compared to neutral facial expression. With this in mind, it is important to design a robust algorithm that can detect the smallest changes.

    Our approach is based on designing an algorithm that receives a real time feed of facial landmark points (see image below). We must emphasise that landmark detection by itself is not sufficient for reliable face gesture detection for use in assistive technology. That’s where our algorithm does the main part of gesture detection.


    Figure 1: Facial landmark points obtained through Android ML Kit Face Detection API.

    In the figure above are displayed facial landmark points (or rather contour points, to use ML Kit’s exact terminology) using our sample demo application “ML Kit landmarks”.
    Demo code available on https://github.com/obstino-org/android_facial_landmarks_demo

    Some challanges that our approach addresses are outlined as follows: – difficult to detect small changes reliably – minimize false detections when user moves their head – allow to adapt detection thresholds: user should be able to choose senstivity to facial movement required to trigger facial gesture detection – detection being responsive enough during use – detect facial gestures reliably during different head tilts

    Smile detection

    Simplified pseudocode

    // function that gets called repeatedly during camera capture
    detectSmile(face) {
        Lx = pixGetMouthWidth(face); // rotation independent (Pythagoras)
        Lnorm = pixGetEyeWidth(face); // obtain eye width (Pythagoras)
    
        // detect translation
        Tx = pixGetNosePosX(face);
        Ty = pixGetNosePosY(face);
    
        if(firstRun) {
            // pass values in function arguments to high-pass filters multiple times
            // --> afterewards, filter outputs will be around 0 as expected initially
            //     during neutral face expression
    
            dx = chargeHighpassFilter1(Lx);
            dTx = chargeHighpassFilter2(Tx);
            dTy = chargeHighpassFilter3(Ty);
        } else {
            // detect differences in movement
            dx = highpassFilter1(Lx); // dx measures smile (mouth width change)
            dTx = highpassFilter2(Tx); // how many pixels nose moved on x-plane
            dTy = highpassFilter3(Ty); // how many pixels nose moved on y-plane
        }
    
        dT = sqrt(dTx^2 + dTy^2); // how many pixels nose actually moved (xy plane)
        dT = dT/Lnorm; // convert from pixel units to percentages (pix/pix cancels pix units)
        factor = exp(-5*dT); // high dT (==head movement) gives low factor
    
        // final equation
        Dnorm = dx/Lnorm; // normalize smile change from pixels to percentage units
        Dnorm = Dnorm * factor; // low factor (close to 0) will disable smile detector
    
        if(Dnorm >= thresh && !disableDetection) {
            disableDetection = true; // disable detection while smile active
            chargeLowpassFilter1(Dnorm); // init moving average filter to value Dnorm
            signalize(SMILE_FOUND);
        }
    
        if(disableDetection) {
            lpf = lowpassFilter1(Dnorm);    // lpf measures moving average of Dnorm
            if(lpf < 0.20 * thresh) // at 20% of detection threshold, enable again
                disableDetection = false;
        }
    }

    Basic idea

    The basic idea is that we will compute differences in mouth corner width. High difference in mouth corner width is detected when a person smiles, and when they stop smiling.
    We use a high-pass filter to detect such changes.

    Additionally, unwanted mouth corner width change is also detected when the head is moved. This is due to the fact that from camera’s perspective, the pixel mouth width is not the same when head is rotated 0° as compared to, say, 30°.
    To tackle the challenge of unwanted head movement triggering false positive detection of a smile, we decided to implement an approach which disables smile detection whenever head movement is detected. We do this by tracking nose movement.

    We also use a moving average filter to help us reliably detect when user stopped the smile facial gesture, allowing us to reenable smile detection (variable disableDetection).

    Commenting particular steps in the smile detection pseudocode

    Normalization step

    As we can see in the pseudocode, when computing head movement change dT, there is a normalization step dT = dT/Lnorm. This is very important because we need to set constant thresholds. For example, it is not meaningful information if we know dT was, say, 20 pixels. This is so because, if the person is further away from the camera, same head movement might result in dT = 10 pixels. For this reason, we normalize values such as dT and dx (the latter becomes Dnorm).
    Normalization works because dividing pixels by pixels cancels out pixel units, leading to percentage (or ratio) units. The meaning of normalized dT in our case is then “what percentage of eye width did the point move?”

    Where is dT used and why

    In code, we use dT to compute factor in such a manner that factor is low (close to 0) whenever head movement change dT is a high value, and high (close to 1) whenever dT is a low value. This means that when we multiply Dnorm = Dnorm * factor, when head movement is high, Dnorm will be close to zero. This is desired behaviour, because it prevents false positive detections of a smile when head position changes.
    We achieve this using an empirically designed exponential decay equation: \(\text{factor}(dT) = e^{-5\times dT}\).
    This equation is convenient, because at \(\text{factor}(dT = 0) = 1\). The value \(-5\) in the exponential decay equation was determined empirically. We can see that evaluating \(\text{factor}(dT = 0.3) = 0.22\) results in quite high attentuation when head (or rather nose) is moved 30% (0.3) of eyewidth distance. If we wanted higher attenuation, we can just set an even more negative value than \(-5\) in the equation.

    Detecting changes using high-pass filters

    Background

    As mentioned, our approach is based on detecting small differences in movement of facial landmark points. In our case, we want to help disabled user control their device using the facial gesture of a smile. For this to work, the algorithm should be tuned in a way that is able to detect both sudden changes in mouth corner width as well as slower.
    Mouth corner width is essentially just a number that we compute (pixels units). Because different people have different mouth width, and because mouth width depends on distance from camera, the number itself will not yield useful information. Therefore, we must be able to track changes in that number.

    There are different ways to approach detecting such a change, but all ways essentially boil down the the same principle: a high-pass filter. Indeed, even if(width[t] - width[t-1] > threshold) is a high-pass filter (1-tap FIR difference filter). It is however not the best one for our use case, as it wouldn’t respond to a slow smile, and it could even overly respond to sudden changes, resulting in multiple detections.

    For this purpose we decided to programmatically implement an IIR (infinite impulse response) filter based on 1st order passive CR filter electronic circuit, which is a high-pass filter variant of the exponential smoothing filter.

    Some benefits of using an CR filter are the following: – compared to FIR filters, in this design we didn’t need to know in advance the exact sampling frequency of the filter – sampling frequency in our case is the dynamically changing Frames Per Second of the camera image feed (depends on device and CPU load that happens when computing facial landmarks); it means how many times per second we provide mouth corner width into the filter – we can dynamically update sampling frequency – compared to FIR filters with fixed set of coefficients, we can here instead easily programmatically change the cutoff frequency – cutoff frequency in high-pass filters means how much the filter will respond to slower changes in input signal (mouth corner width in our case) – because slow changes have a high time duration, they have low frequency – setting a low cutoff frequency will allow those slower, low frequency signals, to pass through, whereas a high cutoff frequency will respond to fast changes only – we can empircally determine the optimal cutoff frequency – CR filter is a well known circuit – only 1 parameter determines the filter, namely the cutoff frequency (not counting sampling frequency) – cutoff frequency is directly related to the time it takes the filter to adapt to changes

    Example high-pass filter output

    We will now demonstrate how the high-pass filter works when detecting a smile using mouth corner width Lx.


    Figure 2: High-pass filter output (dx) with input mouth corner width signal (Lx) during smile facial gesture.


    In the image above, we assumed sample frequency 30 Hz, which is due to typical 30 frame per second camera image feed update.

    For first second (30 frames on horizontal time axis) the user’s mouth corner width corresponded to a neutral expression. However, after 1 second, during a smile, mouth corner width Lx increased to 20 pixels, and went back down to 13 pixels. We can notice it didn’t go back down to 10 pixels, which is understandable because of dynamic nature of facial expressions.

    You can see that after the smile gesture, the green signal needed some time to fall back towards zero, i.e. it needed time to adapt to a new input constant baseline value (value of 13 [pix] in this case). Later we will discuss how to make our high-pass filter adapt to this new input constant baseline faster or slower, though a variable called cutoff frequency – inversely related to the fall time which will also be discussed.

    Now the important thing we achieved here using a high-pass filter is the ability to detect change in mouth corner width. High-pass filter output is shown as a the green signal in the image. As we can see, the filter output dx followed signal Lx, and after the change it slowly returned back to 0 pixels on vertical axis.
    This is very desirable, because it allows us to specify a fixed threshold value used to detect a facial gesture (smile in this case). Threshold can be used because the filter output dx is centered around zero, as opposed to the signal Lx whose baseline value can vary.

    As we can see in the figure above, the output from high-pass filter approaches value 0 after smile gesture has finished. If the filter cutoff frequency was set to a higher value, there might be less response (smaller peak) to slower mouth corner width changes, but it would approach 0 faster.

    Theoretical background on high-pass CR filter

    CR filter is a simple electronic circuit which is designed to allow fast (high-frequency) signals to pass through, and attenuate slow (constant or low-frequency) signals. It is named CR because it consisits of a capacitor (C for capacitance, as measured in farad units) and a resistor (R for resistance, as measured in ohm units).

    As we know, electronic circuits can be simulated on computers, and this is done by solving differential equations through numerical methods.

    CR circuit also has a differential equation that we can use to simulate its behaviour (i.e. changing input and output voltages) on a computer. Without going into too much details, this be obtained through CR filter’s Laplace transfer function, and the differential equation is as follows: \[v_{out}(t) + RC\cdot v_{out}'(t) = RC\cdot v_{in}'(t)\]

    We can substitute \(v_{out}(t) = y[n]\) (output signal), \(v_{in}(t) = x[n]\) (input signal), and obtain the ‘backward differences’ for derivates as \(v_{out}'(t) = \frac{y[n] – y[n-1]}{T_{s}}\) and \(v_{in}'(t) = \frac{x[n] – x[n-1]}{T_{s}}\). Here \(T_s\) is the sampling period that has corresponding sampling frequency \(f_s = 1 / T_s\), which in our case is equal to the frame rate (about 30 frames per second).
    The differential equation then becomes the following difference equation: \[y[n] + RC\left[\frac{y[n] – y[n-1]}{T_s}\right] = RC\left[\frac{x[n] – x[n-1]}{T_s}\right]\] It is also known that for CR filter circuit, the product \(R\cdot C\) is equal to so-called time constant \(\tau = RC\). Expressing this difference equation in terms of \(\tau\) and \(f_s\), we obtain: \[y[n] = \alpha\big(x[n] – x[n-1] + y[n-1] \big)\] where \[\alpha = \frac{\tau f_s}{1 + \tau f_s}\]

    We can readily use the obtained difference equation for \(y[n]\) to compute the filter output at sample \(n\), knowing only input signal values and present and previous time point and filter output at previous time point.

    CR filter also has a so-called ‘cutoff frequency’ \(f_c\), which is a frequency below which signals are more and more attenuated. There holds the relation \(f_c = \dfrac{1}{2\pi \tau}\) which yields \(\alpha = \dfrac{f_s}{f_s + 2\pi f_c}\).

    Since the sampling frequency \(f_s\) is known during image capture code to be up to 30 Hz (camera frame rate, FPS), the only question remains is how to set the cutoff frequency \(f_c\).

    For example, suppose \(f_c = 0.1~\text{Hz}\) and \(f_s = 30~\text{Hz}\), as is the case for our smile detection algorithm. From the \(y[n]\) difference equation above, it can be determined that if \(x[n]=1\), \(x[n-1]=0\) and \(y[n-1]=0\), then \(y[n] = \alpha = \frac{30}{30 + 2\pi\cdot 0.1} \approx 0.98\). Clearly, the high-pass output for a fast changing input signal (from 0 to 1 in this case) will directly follow the input signal, in this case it will immediately reach 98% of the input value.
    Such is the case when cutoff frequency is much lower than the sampling frequency.
    One can determine the \(f_c\) empirically, or by a heuristic such as the desired fall time of the filter. The latter can be computed using CR filter’s unit step response, which is an exponentially decaying function. Fall time, i.e. time it takes the filter to go from 90% to 10% of peak value, can be shown to be equal to \(t_f = \dfrac{2.197}{2\pi f_c}\) or equivalently \(f_c = \dfrac{2.197}{2\pi t_f}\).
    If, for example, one then desires 3 seconds for the value to adapt to the new constant baseline, one then sets \(t_f = 3 ~\text{sec}\), obtaining \(f_c = 0.11~\text{Hz}\), as is the case in our code.

    In our code, we used multiple high-pass fiters, for example one was used for dx computation, another for dTx and dTy. In these filters, we set different cutoff frequency values.

    The filter can be implemented in Java as follows:

    class HighpassFilter {
        private double f_sampling;
        private double f_cutoff;
        private double prev_x = 0;
        private double prev_y = 0;
    
        HighpassFilter(double f_sampling, double f_cutoff) {
            this.f_sampling = f_sampling;
            this.f_cutoff = f_cutoff;
            prev_x = 0;
            prev_y = 0;
        }
    
        void setSamplingFrequency(double f_sampling) {
            this.f_sampling = f_sampling;
        }
    
        void setCutoffFrequency(double f_cutoff) {
            this.f_cutoff = f_cutoff;
        }
    
        double computeSample(double x) {
            double alpha;
            double y;
    
            alpha = (double)f_sampling/(2*PI*f_cutoff + (double)f_sampling);
            y = alpha*prev_y + alpha*(x - prev_x);
    
            prev_y = y;
            prev_x = x;
    
            return y;
        }
    
        double chargeSample(double x) {
            // It takes 5*Tau seconds to 'charge' a RC filter; Tau=1/(2*PI*fc) [sec] and 5 sec = 5*fs samples
            double ret = 0;
            for (int k = 0; k < (int)(5.0*f_sampling / (2.0*PI*f_cutoff)); k++)
                ret = computeSample(x);
            return ret;
        }
    }

    We can see that in the code above, there is also a function called chargeSample. This function is used during the first run of smile detection algorithm (chargeHighPassFilter function in pseudocode). As stated in the pseudocode, this function will pass value from the input argument to a high-pass filters multiple times, after which the filter output will be around 0 as expected initially during neutral face expression. If we didn’t charge the filters on first execution of the algorithm, initially a false positive detection might be triggered. This is so, because a newly initialized filter assumes all past inputs to have been zero, and the filter gets triggered by a neutral face expression (say, 20 pixels) just the same as it would if a smile gesture was present (say, 25 pixels). After charging, however, the filter output is zero for neutral face expression, and positive for a smile gesture (e.g. giving 25 – 20 pixels = 5 pixels at filter output).

    Using a low-pass filter to detect end of gesture

    Background

    We use a low-pass RC filter, also known as exponential moving average filter, in our algorithm. We apply the filter after the smile gesture has been detected in order to reliably detect the end of smile gesture.

    As we can see in the smile detection pseudocode, when the smile has been detected (Dnorm >= thresh), we ‘charge’ this low-pass RC filter using chargeLowpassFilter1(Dnorm);. This function basically passes value Dnorm (normalized mouth corner width difference) through the filter multiple times. This sets the filter output value approximately to Dnorm the next time lowpassFilter1 function is called.

    After the smile detection onset, we need to then detect the end of gesture. We do this by passing new values of Dnorm through the algorithm during each algorithm execution. When low-pass filter output falls below 20% of detection threshold, we can safely say that the gesture has been completed. This is important, because otherwise noise or other facial movement might falsely trigger multiple detections, which is why the low-pass filter plays an important role here.


    Figure 3: Low-pass filter output (lpf) with input mouth corner width signal (Lx) during smile facial gesture.


    As we can see in the figure above, after detection of smile gesture, lowpass filter (blue signal in figure) was charged to value around 8, and slowly followed smile difference value dx (dotted green signal in figure). Slow adaptation to differences in dx using the low-pass filter is appropriate, because during our accessibility application of smile gesture detection, we often detect very small changes, smaller than those in the example figure above. This improves robustness to multiple/false detections, and the rate of how fast/slow the low-pass filter adapts can be varied using different filter cutoff frequencies. More about implementing the RC filter and setting the cutoff frequency will be presented in the following subsection.

    Theoretical background on low-pass RC filter

    From the Laplace transform equation of the low-pass RC filter, the following differential equation can be obtained:

    \[v_{out}(t) + RC v_{out}'(t) = v_{in}(t)\]

    Similarily as we did for the high-pass filter, we substitute \(v_{out}(t) = y[n]\) (output signal), \(v_{in}(t) = x[n]\) (input signal), and \(v_{out}'(t) = \frac{y[n] – y[n-1]}{T_{s}}\) (\(T_s\) being the sampling period, inverse of sampling frequency \(f_s\)).

    Substituting and rearranging we obtain: \[y[n] = \alpha x[n] + (1 – \alpha)x[n-1]\] where \[\alpha = \frac{1}{1 + \tau f_s} = \frac{2\pi f_c}{f_s + 2\pi f_c}\]

    Here we substituted \(\tau = RC = \dfrac{1}{2\pi f_c}\) where \(\tau\) is a time constant and \(f_c\) is RC filter’s cutoff frequency.

    If \(f_c\) is a low value, putting a rapidly changing (high-frequency) signal through the RC filter will produce attenuated or zero output at the filter. On the other hand, putting a slowly changing (low-frequency or constant) signal through the filter will preserve only low-frequency components of the signal at the filter output.

    Just as for the high-pass filter, the time (fall-time \(t_f\)) it takes the low-pass RC filter to discharge from 90% to 10% of its initial value, can be shown to be equal to \(t_f = \dfrac{2.197}{2\pi f_c}\) or equivalently \(f_c = \dfrac{2.197}{2\pi t_f}\).
    If we know desired fall time, the equation above allows us to determine the cutoff frequency for our filter.
    For example, suppose that initially filter output \(y[0] = 10\) and we set \(x[n\gt0]=0\). Now we want to know what cutoff frequency \(f_c\) to use in order for filter output \(y\) to adapt to new value \(0\). If we want this to happen in 1 second, we can simply compute \(f_c = \frac{2.197}{2\pi\times 1} \approx 0.35 Hz\). This then is the frequency we would set in code.

    What follows is low-pass RC filter implementation in Java:

    class LowpassFilter {
        private double f_sampling;  // sampling frequency
        private double f_cutoff;
        private double prev_y = 0;
    
        LowpassFilter(double f_sampling, double f_cutoff) {
            this.f_sampling = f_sampling;
            this.f_cutoff = f_cutoff;
            prev_y = 0;
        }
    
        void setSamplingFrequency(double f_sampling) {
            this.f_sampling = f_sampling;
        }
    
        void setCutoffFrequency(double f_cutoff) {
            this.f_cutoff = f_cutoff;
        }
    
        double computeSample(double x) {
            double alpha;
            double y;
    
            alpha = 2*PI*f_cutoff / (2*PI*f_cutoff + f_sampling);
            y = alpha*x + (1 - alpha)*prev_y;
    
            prev_y = y;
            return y;
        }
    
        double chargeSample(double x) {
            // It takes 5*Tau seconds to 'charge' a RC filter; Tau=1/(2*PI*fc) [sec] and 5 sec = 5*fs samples
            double ret = 0;
            for (int k = 0; k < (int)(5.0*f_sampling / (2.0*PI*f_cutoff)); k++)
                ret = computeSample(x);
            return ret;
        }
    }

    Mouth open detection

    Simplified pseudocode

    // function that gets called repeatedly during camera capture
    detectMouthOpen(face) {
        Lx = pixGetMouthWidth(face); // rotation independent (Pythagoras) -- distance between mouth corners
        Ly = pixGetMouthHeight(face); // rotation independent (Pythagoras) -- distance between upper and lower mid lip
        Lnorm = pixGetEyeWidth(face); // (Pythagoras)
    
        // detect translation
        Tx = pixGetNosePosX(face);
        Ty = pixGetNosePosY(face);
    
        mouthRatio = Ly/Lx;
    
        if(firstRun) {
            // pass values in function arguments to filters multiple times
            // --> afterewards, high-pass filter outputs will be around 0 as expected initially, and low-pass filter output will be equal to Ly
    
            fy = chargeLowpassFilter1(Ly);
            dTx = chargeHighpassFilter1(Tx);
            dTy = chargeHighpassFilter2(Ty);
        } else {
            // detect differences in movement
            fy = lowpassFilter1(Ly); // fy measures mouth open (mouth height)
            dTx = highpassFilter1(Tx); // how many pixels nose moved on x-plane
            dTy = highpassFilter2(Ty); // how many pixels nose moved on y-plane
        }
    
        dT = sqrt(dTx^2 + dTy^2); // how many pixels nose actually moved (xy plane)
        dT = dT/Lnorm; // convert from pixel units to percentages (pix/pix cancels pix units)
        factor = exp(-5*dT); // high dT (==head movement) gives low factor
    
        // final equation
        Dnorm = fy/Lnorm; // normalize mouth open distance from pixels to percentage units
        Dnorm = Dnorm * factor; // low factor (close to 0) will disable mouth open detector
    
        if(Dnorm >= thresh && mouthRatio >= 0.25 && !disableDetection) {
            disableDetection = true; // disable detection while mouth open active
            signalize(MOUTH_OPEN);
        }
    
        if(disableDetection) {
            if(Dnorm < 0.40 * thresh) // at 40% of detection threshold, enable again
                disableDetection = false;
        }
    }

    Comment

    The principle of functioning is similar as with smile detection. First difference here is that we use a low-pass filter as a primary tool to detect mouth open. Similar as with smile detection, we normalize mouth open from pixel units to percentage units (or ratios) by dividing mouth open distance by eye width in pixels. This done by the line Dnorm = fy/Lnorm, where fy is the moving average of mouth open distance and Lnorm is eye width in pixels. This effectively gives us Dnorm, which gives the mouth open distance as a percentage of eye width.

    Another difference as compared to smile detection code is that here two triggers have to happen in order for the code to reliably register detection. The first is Dnorm >= thresh, and another is given as mouthRatio >= 0.25.
    Here mouthRatio is the ratio between mouth open height and mouth corner width.

    Other than the two named differences, the principle of false positive detection prevention code is based the same way as in smile detection code, namely by attenuating mouth open distance Dnorm when head movement is detected (Dnorm = Dnorm * factor in the code above).

    Detecting eyebrow raise

    Simplified pseudocode

    // function that gets called repeatedly during camera capture
    detectEyebrowRaise(face) {
        Lnorm = pixEyeWidth(face);  // rotation independent (Pythagoras)
        
        // compute angle (alpha = asin(y/D)) -- see figure 5
        angle = arcsin(eyeCornerHeightDiff / eyeCornerDistance) // compute head side tilt (roll angle)
        Ly = pixNoseToEyebrowDistance(face, angle); // note that eyebrow position is average of 4 eyebrow landmark points (Ly is rotation independent)
        
        // detect translation
        Tx = pixGetNosePosX(face);
        Ty = pixGetNosePosY(face);
        
        if(firstRun) {
            // pass values in function arguments to high-pass filters multiple times
            // --> afterewards, filter outputs will be around 0 as expected initially
            //     during neutral face expression
            
            dy = chargeHighpassFilter1(Ly);
            dTx = chargeHighpassFilter2(Tx);
            dTy = chargeHighpassFilter3(Ty);
        } else {
            // detect differences in movement
            dy = highpassFilter1(Ly); // dy measures eyebrow raise (nose to eyebrow distance change)
            dTx = highpassFilter2(Tx); // how many pixels nose moved on x-plane
            dTy = highpassFilter3(Ty); // how many pixels nose moved on y-plane
        }
    
        dT = sqrt(dTx^2 + dTy^2); // how many pixels nose actually moved (xy plane)
        dT = dT/Lnorm; // convert from pixel units to percentages (pix/pix cancels pix units)
        factor = exp(-5*dT); // high dT (==head movement) gives low factor
    
        // final equation
        Dnorm = dy/Lnorm; // normalize eyebrow change from pixels to percentage units
        Dnorm = Dnorm * factor; // low factor (close to 0) will disable eyebrow raise detector
    
        if(Dnorm >= thresh && !disableDetection) {
            disableDetection = true; // disable detection while eyebrow raise active
            chargeLowpassFilter1(Dnorm); // init moving average filter to value Dnorm
            signalize(EYEBROW_RAISE_FOUND);
        }
    
        if(disableDetection) {
            lpf = lowpassFilter1(Dnorm);    // lpf measures moving average of Dnorm
            if(lpf < 0.20 * thresh) // at 20% of detection threshold, enable again
                disableDetection = false;
        }
    }

    Comment

    The code is most similar to smile detection in the following way: – a highpass filter is used to detect a change in eyebrow height level – a lowpass filter is used to detect the end of eyebrow raise gesture – highpass filters are used to detect head movement, disabling detection when such movement is present

    The distance Ly from pseudocode is illustrated in the Figure 4 below.


    Figure 4: Demonstration of distance Ly in eyebrow raise detection code. The 4 green points on eyebrow and 1 green point on nose illustrate a selected subset of landmark points used to detect eyebrow raise.



    Figure 5: Demonstration of head side tilt computation using landmark points (green) on the outer corners of the eyes. Here α corresponds to ‘angle’ in pseudocode, whereas y and D correspond to ‘eyeCornerHeightDiff’ and ‘eyeCornerDistance’ in pseudocode.


    The most important things about eyebrow raise detection code are the following:

    1. The algorithm doesn’t measure only eyebrow position differences.
      We don’t merely measure when positions of eyebrow pixels changes, because this would give false detections when head is moved. Instead we measure differences in distance between nose position and between eyebrow position (distance Ly in Figure 4). Additionally that distance is normalized with respect to eye width in pixels, making the algorithm robust to head movement towards and away from the camera.
    2. We make sure the algorithm works even when head is tilted (side tilts left/right, i.e. roll angle). This is important because some users’ neutral head positions during usage may vary (for example due to their condition). We compute head angle using trigonometric functions, using points around eyes as input to this calculations (see Figure 5).
    3. Eyebrow position is computed by using the average of 4 green points on left eyebrow (Figure 4), for most reliable detection.

    Conclusion

    In this article we introduced our accessibility Android application Face Control, and described in detail the algorithms we implemented and the mathematical background that enable it to achieve robust detection of facial gestures. The gestures described are detection of smile, mouth open and eyebrow raise.

    The advantage of our approach is that it doesn’t require many parameters in order for it to work. Instead the approach is robust under different frame rates of camera capture, and is ready to use without complex setup. Even so, if users desire higher sensitivity to facial gesture detection, the approach allows for easy programmatical adjustability of the parameters, as is the case in our implementation of Face Control.

    In the article for most part the gesture detection code is written in pseudocode, however the reader is invented to view the full Face Control app Java source code, available freely on GitHub (https://github.com/obstino-org/facecontrol).