Calculate the distance and angle of your device with regards to your face

Overview

EVFaceTracker

TL;DR: Use face detection for calculating distance and angle of your phone.

Build Status Issues Stars Version License Platform Documentation

Git Twitter LinkedIn Website eMail

Here is a demo where this is used for setting the shadow and size of a text.

Screenshot0

For a longer demo see: https://www.youtube.com/watch?v=yLAtc7AzjIk

Introduction

Earlier this month I had a discussion with a colleague about new forms of user interaction. On mobile devices there are now many applications that are using the compass and or accelerator. On a game consoles it’s very common to use a camera to interact with a game (Xbox Kinect and Playstation move) I thought it would be nice if we could use the front facing camera of a phone for interacting with an app. I had to see if this idea could be implemented.

Since iOS 5 Apple has added a face detection api. My idea was to detect a face and estimate the distance the device is from your face based on the size of the detected face. If the rectangle of the detected face is big, then the device is close to your face, if it’s small, then the device is far away from your face. With a similar technique it is also possible to calculate the angle of the device in relation to the face. This angle is calculated based on how fare the detected face rectangle is away from the center of the screen.

The challenge here was to hook into the video stream and detect the face for each frame. Fortunately Apple has a sample project for this called SquareCam. With the code from that project it’s possible to detect faces in about 5 frames per second (on an iPhone 4S)

There are a couple of fun things that you could do with face tracking:

  • Change the zoom level based on the distance.
  • Change the shadow offset based on the angle
  • ?

Using EVFaceTracker in your own App

'EVFaceTracker' is now available through the dependency manager CocoaPods. You can install cocoapods by executing:

[sudo] gem install cocoapods

If you have installed cocoapods, then you can just add EVFaceTracker to your workspace by adding the following line to your Podfile:

pod "EVFaceTracker"

You can also just copy EVFaceTracker.m and .h to your project.

The demo code:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Start tracking your face.
    evFaceTracker = [[EVFaceTracker alloc] initWithDelegate:self];
    // And give us a smooth update 10 times per second.
    [evFaceTracker fluidUpdateInterval:0.1f withReactionFactor:0.5f];
}

#pragma mark - <EVFaceTrackerDelegate>
// This delegate method is called every time the face recognition has detected something (including change)
- (void)faceIsTracked:(CGRect)faceRect withOffsetWidth:(float)offsetWidth andOffsetHeight:(float)offsetHeight andDistance:(float) distance {
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.2];
    CALayer *layer = dynamicLabel.layer;
    layer.masksToBounds = NO;
    layer.shadowOffset = CGSizeMake(offsetWidth / 5.0f, offsetHeight / 10.0f);
    layer.shadowRadius = 5;
    layer.shadowOpacity = 0.5;
    [CATransaction commit];
}

// When the fluidUpdateInterval method is called, then this delegate method will be called on a regular interval
- (void)fluentUpdateDistance:(float)distance {
    // Animate to the zoom level.
    float effectiveScale = distance / 60.0f;
    [CATransaction begin];
    [CATransaction setAnimationDuration:0.1f];
    [dynamicView.layer setAffineTransform:CGAffineTransformMakeScale(effectiveScale, effectiveScale)];
    [CATransaction commit];
}

License

EVFaceTracker is available under the MIT 3 license. See the LICENSE file for more info.

My other libraries:

Also see my other open source iOS libraries:

  • EVReflection - Reflection based (Dictionary, CKRecord, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift
  • EVCloudKitDao - Simplified access to Apple's CloudKit
  • EVFaceTracker - Calculate the distance and angle of your device with regards to your face in order to simulate a 3D effect
  • EVURLCache - a NSURLCache subclass for handling all web requests that use NSURLReques
  • AlamofireOauth2 - A swift implementation of OAuth2 using Alamofire
  • EVWordPressAPI - Swift Implementation of the WordPress (Jetpack) API using AlamofireOauth2, AlomofireJsonToObjects and EVReflection (work in progress)
  • PassportScanner - Scan the MRZ code of a passport and extract the firstname, lastname, passport number, nationality, date of birth, expiration date and personal numer.
  • AttributedTextView - Easiest way to create an attributed UITextView with support for multiple links (url, hashtags, mentions).
You might also like...
Zeplin component preview for your SwiftUI views
Zeplin component preview for your SwiftUI views

A Zeplin component preview for your SwiftUI views. You can use Zeplin components instead of real views within your app until you implement them.

Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements
Easily use UIKit views in your SwiftUI applications. Create Xcode Previews for UIView elements

SwiftUIKitView Easily use UIKit views in SwiftUI. Convert UIView to SwiftUI View Create Xcode Previews from UIView elements SwiftUI functional updatin

Confetti View lets you create a magnificent confetti view in your app
Confetti View lets you create a magnificent confetti view in your app

ConfettiView Confetti View lets you create a magnificent confetti view in your app. This was inspired by House Party app's login screen. Written in Sw

DGFadingLabel - A custom UILabel that fades away the end of your text when text is too large to fit within the label's frame
DGFadingLabel - A custom UILabel that fades away the end of your text when text is too large to fit within the label's frame

A custom UILabel that fades away the end of your text when text is too large to fit within the label's frame.

Safari Web Extension to customize your search engine.
Safari Web Extension to customize your search engine.

Safari Web Extension to customize your search engine. Search queries made from the Safari address bar are appended to the custom search engine URL. No

A custom stretchable header view for UIScrollView or any its subclasses with UIActivityIndicatorView and iPhone X safe area support for content reloading. Built for iOS 10 and later.

Arale A custom stretchable header view for UIScrollView or any its subclasses with UIActivityIndicatorView support for reloading your content. Built f

🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0
🏞 A simple iOS photo and video browser with optional grid view, captions and selections written in Swift5.0

Introduction 🏞 MediaBrowser can display one or more images or videos by providing either UIImage objects, PHAsset objects, or URLs to library assets,

MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding support for iPhone and additional opportunities to setup UIPresentationController size and feel form sheet.
MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding support for iPhone and additional opportunities to setup UIPresentationController size and feel form sheet.

MZFormSheetPresentationController MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding sup

Step-by-step progress view with labels and shapes. A good replacement for UIActivityIndicatorView and UIProgressView.
Step-by-step progress view with labels and shapes. A good replacement for UIActivityIndicatorView and UIProgressView.

StepProgressView Step-by-step progress view with labels and shapes. A good replacement for UIActivityIndicatorView and UIProgressView. Usage let progr

Comments
  • Could not find CIDetector

    Could not find CIDetector

    Hey, apologies for my lack of knowledge in Objective C - I'm actually looking at if it's possible to port this to ReactNative. Running this in my project I get :

    /Users/kyle/rnfacetracking/ios/Pods/Headers/Public/EVFaceTracker/EVFaceTracker.h:22:5: Unknown type name 'CIDetector'
    

    I fixed this by adding the following to EvFaceTracker.h

    #import <CoreImage/CoreImage.h>
    

    Is this correct or am I missing something?

    opened by kyle-ssg 2
  • is it possible 10 feet distance mesaure?

    is it possible 10 feet distance mesaure?

    Hello,

     This is good demo to distance measure but it's measuring now only 2feet I want to upto 10 feet how it is possible?
    

    Thanks & Ragards, Vishal.

    question 
    opened by vnanaware 1
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 1
Owner
Edwin Vermeer
Edwin Vermeer
Lightweight touch visualization library in Swift. A single line of code and visualize your touches!

TouchVisualizer is a lightweight pure Swift implementation for visualising touches on the screen. Features Works with just a single line of code! Supp

Morita Naoki 851 Dec 17, 2022
Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle.

Twinkle ✨ Twinkle is a Swift and easy way to make any UIView in your iOS or tvOS app twinkle. This library creates several CAEmitterLayers and animate

patrick piemonte 600 Nov 24, 2022
Fetch the star wars api from all the planets and list and show details using Swift UI and Combine

Star Wars Planets Fetch the star wars planet data by using stat war api, list and show details using SwiftUI and Combine frameworks ?? Swift UI Framew

null 1 Aug 10, 2022
Circular progress indicator for your macOS app

CircularProgress Circular progress indicator for your macOS app This package is used in production by apps like Gifski and HEIC Converter. Requirement

Sindre Sorhus 520 Jan 3, 2023
Show progress in your app's Dock icon

DockProgress Show progress in your app's Dock icon This package is used in production by the Gifski app. You might also like some of my other apps. Re

Sindre Sorhus 958 Jan 2, 2023
A child view controller framework that makes setting up your parent controllers as easy as pie.

Description Family is a child view controller framework that makes setting up your parent controllers as easy as pie. With a simple yet powerful publi

Christoffer Winterkvist 246 Dec 28, 2022
A fancy hexagonal layout for displaying data like your Apple Watch

Hexacon is a new way to display content in your app like the Apple Watch SpringBoard Highly inspired by the work of lmmenge. Special thanks to zenly f

Gautier Gédoux 340 Dec 4, 2022
LicensePlist is a command-line tool that automatically generates a Plist of all your dependencies, including files added manually

LicensePlist is a command-line tool that automatically generates a Plist of all your dependencies, including files added manually(specifi

Masayuki Ono (mono) 2.2k Dec 29, 2022
An iOS picker view to serve all your "picking" needs

Mandoline The PickerView is a UICollectionView that provides a smooth "picking" interface. In order to get the most out of it, a consuming view contro

Blue Apron 883 Nov 28, 2022
⚙ Add a preferences window to your macOS app in minutes

Preferences Add a preferences window to your macOS app in minutes Just pass in some view controllers and this package will take care of the rest. Requ

Sindre Sorhus 1.2k Jan 6, 2023