Age + Gender Estimation on Android - with TensorFlow Lite

Overview

Age + Gender Estimation in Android with TensorFlow

repo_banner


Contents

Python project

Android project

Issues and Suggestions

License


results


🖥️ Python Project

👉🏻 Colab Notebooks

As the application uses two different models for age and gender estimation, we provide two notebooks to train the age and gender detection models. These are Google Colab notebooks and are capable of downloading the dataset, training the model, and finally exporting the TFLite model ( used in the Android app ).

Open In Colab

Open In Colab

The notebooks describe each step in the implementation and are self explanatory. For any questions/issues/suggestions regarding the notebooks, see Issues and Suggestions

The Keras models ( .h5 ) are available here,

👉🏻 Dataset

The TensorFlow models are trained on the UTKFace dataset which contains 23K images with age, gender and ethnicity annotations. We use 20K samples from the dataset, in which 14K images are used for training and 6K images are used to evaluate the model.

For both the models, we use 3-channeled RGB images as inputs. The age estimation model takes in 200 * 200 images as inputs whereas the gender classification model takes in images of size 128 * 128.

  • For the age estimation model, we normalize the target variable i.e the age of the person. Hence the model's output is in the range ( 0 , 1 ]. The predicted age is obtained by multiplying the model's output with a suitable factor ( which in our case is 116 ).
  • For gender classification, the model outputs a probability distribution for the two labels male and female .

👉🏻 Model

We provide two different variants of our models. We refer these variants as vanilla and lite. The lite models are identical to the vanilla models except that they use separable convolutions instead of the standard convolutions. You'll notice the change in the Colab notebook,

# Define the conv block.
if lite_model:
        x = tf.keras.layers.SeparableConv2D( num_filters ,
                                            kernel_size=kernel_size ,
                                            strides=strides 
                                            , use_bias=False ,
                                            kernel_initializer=tf.keras.initializers.HeNormal() ,
                                            kernel_regularizer=tf.keras.regularizers.L2( 1e-5 )
                                             )( x )
 else:
        x = tf.keras.layers.Conv2D( num_filters ,
                                   kernel_size=kernel_size ,
                                   strides=strides ,
                                   use_bias=False ,
                                   kernel_initializer=tf.keras.initializers.HeNormal() ,
                                   kernel_regularizer=tf.keras.regularizers.L2( 1e-5 )
                                    )( x )
 
    x = tf.keras.layers.BatchNormalization()( x )
    x = tf.keras.layers.LeakyReLU( leaky_relu_alpha )( x )

Separable Convolutions have lesser parameters than standard convolutions, and hence reduce the size of our model. Also, the lite models run faster as compared to their vanilla counterparts. The increase in speed is companioned with a slight decrease in the performance of the model as shown below,

Model ( Age Estimation ) vanilla model lite model
No. of parameters 1,069,297 200,956
MAE 2.425 4.586
Model ( Gender Classification ) vanilla model lite model
No. of parameters 675,090 328,733
Accuracy ( % ) 99.8 96.4

📱 Android Project

👉🏻 Overview

The following GIF displays the basic functionality of the app. You may observe the four options provided for "Choose Model" and also the NNAPI and GPU Delegate options. The inference time may change depending on the device you're using.

working_of_app

👉🏻 Usage

  • Open the app. A dialog box saying "Initialize a Model" pops up. Select any one of the four models.
  • Select the additional options, like "Use NNAPI" and "Use GPU". If any of these options are not available on your device, a message will be shown for the same. See NNAPI and GpuDelegate compatibility
  • Once the models are initialized, tap "Take Photo" to open the default camera app.
  • If none of the faces are identified in the picture, a dialog will be displayed, prompting you to take another picture. If everything goes fine, the results appear on the screen in a couple of seconds.
  • Tap "Reinitialize" to try another model provided in the app.

Note: If the picture clicked by the user contains multiple faces, results will be shown for a single face only. This is a drawback and we'll try to improve it in the next releases.

👉🏻 Project Configuration

The project has been configured with the below settings, which can be easily found in the app's build.gradle file.

// SDK Info
compileSdkVersion 30  
buildToolsVersion "30.0.0"  

// App info
applicationId "com.ml.projects.age_genderdetection"  
minSdkVersion 23  
targetSdkVersion 30  

// Version info
versionCode 1  
versionName "1.0"

The versions of the Android Gradle plugin and the Gradle Version are mentioned below.

Android Gradle Plugin Version: 4.1.3
Gradle Version: 6.5

As mentioned, the project utilizes Firebase, and specifically MLKit FaceDetector. To connect the app with Firebase, follow these instructions. Download the google-services.json file and place it in the app folder. The Firebase library required for the face detection functionality is added in the app's build.gradle,

implementation 'com.google.android.gms:play-services-mlkit-face-detection:16.1.5'

Why isn't the google-services.json file shared alongside the code in this repo? That's because the file contains credentials unique for every user. ( You may need to create a Firebase project. Follow the instructions cited above )

👉🏻 TensorFlow Lite models

To enable TFLite capabilities in our Android project, we add the below libraries to our project,

implementation 'org.tensorflow:tensorflow-lite:2.4.0'  
implementation 'org.tensorflow:tensorflow-lite-gpu:2.4.0'  
implementation 'org.tensorflow:tensorflow-lite-support:0.1.0'

See the packages on JFrog Bintray.

All TFLite models are placed in the app's assets folder. In order to disable the compression performed on files present in the assets folder, we add the following flag in app's build.gradle ,

android {  
  ...
  aaptOptions {  
     noCompress "tflite"  
  }
  ...
}  

The names of these models are stored in the modelFilenames array in MainActivity.kt,

private val modelFilenames = arrayOf(  
    arrayOf("model_age_q.tflite", "model_gender_q.tflite"),  
    arrayOf("model_age_nonq.tflite", "model_gender_nonq.tflite"),  
    arrayOf("model_lite_age_q.tflite", "model_lite_gender_q.tflite"),  
    arrayOf("model_lite_age_nonq.tflite", "model_lite_gender_nonq.tflite"),  
)

Whenever the user selects a particular model, we use the FileUtil.loadMappedFile() method to get MappedByteBuffer of the model, which is then passed to the constructor of Interpreter,

ageModelInterpreter = Interpreter(FileUtil.loadMappedFile( applicationContext , "model_v6_age_q.tflite"), options )

Note: The method FileUtil.loadMappedBuffer() comes from the tf-lite-support library, which helps us parse TFLite models and also to preprocess model inputs.

👉🏻 NNAPI and GpuDelegate compatibility

The app offers acceleration through the means of NNAPI and GpuDelegate provided by TensorFlow Lite.

As mentioned in the docs, NNAPI is compatible for Android devices running Android Pie ( API level 27 ) and above. The app checks this compatibility in MainActivity.kt,

if ( Build.VERSION.SDK_INT < Build.VERSION_CODES.P ) {  
    useNNApiCheckBox.isEnabled = false  
    useNNApiCheckBox.text = "Use NNAPI ( Not available as your Android version is less than 9 ( Android Pie )."  
    useNNApi = false  
}

The GpuDelegate also performs the following compatibility check,

if ( !compatList.isDelegateSupportedOnThisDevice ){  
    useGPUCheckBox.isEnabled = false  
    useGPUCheckBox.text = "Use GPU ( GPU acceleration is not available on this device )."  
    useGpu = false  
}

🔧 Issues and Suggestions

If any issue occurs, you may open an issue or start a new discussion. Please mention the following while addressing your issue,

  • The name of the device you're using ( along with its Android version ).
  • Crash logs if you think they might be helpful.
  • If you've found something related to the issue elsewhere, mention them as well so that the issue could be resolved as fast as possible.

👨🏻‍✈️ License

MIT License  
  
Copyright (c) 2021 Shubham Panchal  
  
Permission is hereby granted, free of charge, to any person obtaining a copy  
of this software and associated documentation files (the "Software"), to deal  
in the Software without restriction, including without limitation the rights  
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell  
copies of the Software, and to permit persons to whom the Software is  
furnished to do so, subject to the following conditions:  
  
The above copyright notice and this permission notice shall be included in all  
copies or substantial portions of the Software.  
  
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR  
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,  
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE  
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER  
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,  
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  
SOFTWARE.
You might also like...
:movie_camera: Movie discovery app showcasing Android best practices with Google's recommended architecture: MVVM + Repository + Offline support + Android Architecture Components + Paging library & Retrofit2.
:movie_camera: Movie discovery app showcasing Android best practices with Google's recommended architecture: MVVM + Repository + Offline support + Android Architecture Components + Paging library & Retrofit2.

Popular Movies Stage 1 + Stage 2 Discover the most popular and top rated movies playing. Movies data fetched using themoviedb.org API. ✨ Screenshots M

Extensible Android mobile voice framework: wakeword, ASR, NLU, and TTS. Easily add voice to any Android app!
Extensible Android mobile voice framework: wakeword, ASR, NLU, and TTS. Easily add voice to any Android app!

Spokestack is an all-in-one solution for mobile voice interfaces on Android. It provides every piece of the speech processing puzzle, including voice

Aggregated Android news, articles, podcasts and conferences about Android Development
Aggregated Android news, articles, podcasts and conferences about Android Development

DroidFeed Curated news feed for Android Developers! Stay up to date with the latest Android Development news. Built for the Android developer communit

 🍲Foodium is a sample food blog Android application 📱 built to demonstrate the use of Modern Android development tools - (Kotlin, Coroutines, Flow, Dagger 2/Hilt, Architecture Components, MVVM, Room, Retrofit, Moshi, Material Components). A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar
A simple app to showcase Androids Material Design and some of the cool new cool stuff in Android Lollipop. RecyclerView, CardView, ActionBarDrawerToggle, DrawerLayout, Animations, Android Compat Design, Toolbar

#Android-LollipopShowcase This is a simple showcase to show off Android's all new Material Design and some other cool new stuff which is (new) in Andr

The Android startup used to schedule tasks, jobs while launching Android App.

Android Startup, schedule your startup jobs Introduction AndroidStartup is an open source project used to refine your Andriod App startup. Compared wi

Android playground project with modularization by feature (android libraries), unit tests, MVVM & MVI.
Android playground project with modularization by feature (android libraries), unit tests, MVVM & MVI.

Movies Movies is a simple project to study and play with some android components, architecture and tools for Android development. Tech Stack This proj

🌄 Photo editor using native modules for iOS and Android. Inherit from 2 available libraries, Brightroom (iOS) and PhotoEditor (Android)
🌄 Photo editor using native modules for iOS and Android. Inherit from 2 available libraries, Brightroom (iOS) and PhotoEditor (Android)

React Native Photo Editor (RNPE) 🌄 Image editor using native modules for iOS and Android. Inherit from 2 available libraries, Brightroom (iOS) and Ph

Ride-Sharing Uber Lyft Android App - Learn to build a ride-sharing Android Taxi Clone App like Uber, Lyft - Open-Source Project By MindOrks
Ride-Sharing Uber Lyft Android App - Learn to build a ride-sharing Android Taxi Clone App like Uber, Lyft - Open-Source Project By MindOrks

Ride-Sharing Uber Lyft Android App - Learn to build a ride-sharing Android Taxi Clone App like Uber, Lyft - Open-Source Project By MindOrks

Releases(v1.0)
Owner
Shubham Panchal
The BEST WAY to PREDICT THE FUTURE is to INVENT it ...
Shubham Panchal
This document will walk you through the steps for creating your Android app that runs a deep learning image classification model trained in Pocket AutoML and exported in TensorFlow Lite format

Pocket AutoML: Tutorial for Creating an Android App for Image Classification with Deep Learning Translations English (this document) Русский Overview

Evgeniy Mamchenko 15 Nov 22, 2022
This app using Mlkit along with the TensorFlow Lite model for object detection,

I built this app using Mlkit along with the TensorFlow Lite model for object detection, Arcore is used to place anchors to the detected objects. It's a good blend of Machine learning and Augmented reality to visualise ML information in a much better way than regular bounding boxes

Kashif Mehmood 18 Nov 10, 2022
Gender Checker app built using Kotlin, MVVM, Genderize.io API. Take this as a reference for MVVM and Genderize.io API 🚀

Gender-Checker ?? Gender Checker app built using Kotlin, MVVM, Genderize.io API Enter a name and the app will guess the gender ?? ✨ Highligts: API : G

Jai Keerthick 0 Jan 5, 2022
Android Chinese TTS Engine Base On Tensorflow TTS , use for TfLite Models Test。安卓离线中文TTS引擎,在TensorflowTTS基础上开发,用于TfLite模型测试。

Chinese TTS TF Lite 介绍 使用Kotlin + JetPack Compose + Tensorflow Lite开发的TTS引擎,可以完全离线使用。 可选两种模型:FastSpeech和Tacotron,这两种模型均来自TensorFlowTTS 文字转拼音方法来自:Tenso

benjamin wan 116 Jan 2, 2023
Cracking Age Passphrases

Age passpharse cracking I created this library as a help to break an AGE passphrase at a security conference. Learn more about the age encryption proj

Jamie Visker 2 Oct 25, 2021
Android-Java-App - Notepad app with user and password. SQL Lite

DVNote2 App Android-Java-App Notepad app with user and password Application made in Android Studio with Java language and SQLite database. How does it

DViga 1 Nov 6, 2021
android-delicious Delicious Android is an Android app which helps you access and save bookmarks via Delicious. It's available over at Google Play.

Delicious Android Delicious Android is an Android app which helps you access and save bookmarks via Delicious. It's available over at Google Play. Fea

Alexander Blom 137 Nov 20, 2022
Android cutout screen support Android P. Android O support huawei, xiaomi, oppo and vivo.

CutoutScreenSupport Android cutout screen support Android P. Android O support huawei, xiaomi, oppo and vivo. Usage whether the mobile phone is cutout

hacket 5 Nov 3, 2022
FoldingNavigationDrawer-Android This is a sample project present how to use Folding-Android to add Folding Efect to Navigation Drawer.

FoldingNavigationDrawer-Android Sample (Play Store Demo) This is a sample project present how to use Folding-Android to add Folding Efect to Navigatio

null 242 Nov 25, 2022
Twidere-Android Twidere is a powerful twitter client for Android 1.6+ 1 , which gives you a full Holo experience and nearly full Twitter's feature.

Twidere for Android Material Design ready and feature rich Twitter/Mastodon/Fanfou app for Android 4.1+. Enjoy Fediverse now! Twidere-Android is maint

Twidere Project 2.7k Jan 2, 2023