TensorFlow Lite Image recognition: Android with Kotlin

Teresa Wu
2 min readApr 3, 2018

--

TensorFlow is a wonderful tool for machine learning, where its main purpose is designed for neural network models. When it comes to mobile, Google has provided us with two libraries: TensorFlow mobile and TensorFlow Lite.

They both works on Android and iOS. While TensorFlow mobile is recommended to use for developers who have a pre-trained model (a trained model is like the brain, which teaches the system how to recognise objects), TensorFlow Lite is the lightweight solution that comes with a pre-tested model with 1000 predefined classes. (to read more on TensorFlow)

In this tutorial, we will use TensorFlow Lite as an example.

Step 1: Set up the project

I am going to jump the steps of creating new project on Android studio and assuming you have a project that runs. So here is what we need in module level gradle:

buildscript {
repositories {
maven { url 'https://google.bintray.com/tensorflow'}
}
}
android {
aaptOptions {
noCompress "tflite"
noCompress "lite"
}
}
dependencies {
implementation 'org.tensorflow:tensorflow-android:+'
}

Step 2: Add models and label file

Add label.txt and .tflite files in: myproject/app/src/main/assets (github link to download the file)

Step 3: Layout file

This is a simple layout, which has a TextView to display results and an ImageView to display a picture for your model to read:

Step 4: Kotlin classes and functions

Create classes to hold data and to print out formatted results:

Now we need a classifier class to recognise the image, usually this could be as simple as to create an Interpreter object and fire interpreter.run( ), but because we are dealing with images, you also need to parse the image and resize it. The following code is taking from Google TensorFlow Android sample project, where I have simplied and converted to Kotlin:

Last step is to create the view class, so we can run and play the app:

Note: Bitmap.createScaleBitmap is a very important step, without it you might get “ArrayOutOfIndexException”. This is because the sample image has to be same size as the model image, and I will explain the reason behind it in another post, where I talk more about how to train your own model.

I have talked about how to train your own model in this post, where results can be personalised, so instead of giving result as a dog, you can customise the result to be “Molly”. Here is a link of some pre-trained models.

Let me know how you liked this TensorFlow Lite tool and your testing results with the model. Full code is available here

--

--

Teresa Wu
Teresa Wu

Written by Teresa Wu

Enthusiastic about cloud technology, data, clean code, Flutter, and Agile

Responses (3)