Sub topic 11
Running the Model Inside an Android or iOS App
Assume you know Python, tensors, image preprocessing, and basic Android or iOS development. This chapter focuses on the mobile integration boundary: loading a converted model, preparing camera frames, running inference, and presenting results.
A mobile app usually performs this pipeline:
Choose the app integration shape
You can run inference in several places:
| Integration shape | Best use | Main concern |
|---|---|---|
| On-device inference | Low latency, offline use, private images | Device CPU, GPU, or NPU limits |
| Server inference | Large models and centralized updates | Network delay, cost, and privacy |
| Hybrid inference | Fast local result with optional cloud fallback | More complex product behavior |
For on-device inference, keep the model loaded while the screen is active. Loading it for every camera frame wastes time and memory.
TensorFlow Lite, ONNX Runtime, Core ML, and ExecuTorch provide similar responsibilities. Each loads a model, accepts tensors, executes operators, and returns tensors. The file format and accelerator support differ. Core ML is the natural choice for many Apple-only apps. TensorFlow Lite or ONNX Runtime can be useful when one model must support both Android and iOS.
Match preprocessing exactly
The app must reproduce the preprocessing used during training. This includes color order, image size, crop method, numeric range, and normalization.
For example, a model trained with 224 by 224 RGB images may expect either:
- Float values in the range 0 to 1.
- Float values normalized by a mean and standard deviation.
- Quantized uint8 values with a model-specific scale and zero point.
A mismatch can produce plausible-looking but incorrect predictions.
Android example with TensorFlow Lite
The following Kotlin example assumes an asset named model.tflite. It reads the model's input shape and data type, creates a uint8 input tensor from a bitmap, and returns the output scores.
import android.content.Context
import android.graphics.Bitmap
import org.tensorflow.lite.Interpreter
import java.nio.ByteBuffer
import java.nio.ByteOrder
class ImageClassifier(context: Context) {
private val interpreter: Interpreter
init {
val model = context.assets.open("model.tflite").use { input ->
input.readBytes()
}
val buffer = ByteBuffer.allocateDirect(model.size)
.order(ByteOrder.nativeOrder())
buffer.put(model)
buffer.rewind()
interpreter = Interpreter(buffer)
}
fun classify(bitmap: Bitmap): FloatArray {
val inputInfo = interpreter.getInputTensor(0)
val shape = inputInfo.shape()
val height = shape[1]
val width = shape[2]
val resized = Bitmap.createScaledBitmap(bitmap, width, height, true)
val input = ByteBuffer.allocateDirect(width * height * 3)
.order(ByteOrder.nativeOrder())
for (y in 0 until height) {
for (x in 0 until width) {
val pixel = resized.getPixel(x, y)
input.put((pixel shr 16 and 0xff).toByte())
input.put((pixel shr 8 and 0xff).toByte())
input.put((pixel and 0xff).toByte())
}
}
input.rewind()
val output = Array(1) { FloatArray(1000) }
interpreter.run(input, output)
return output[0]
}
fun close() {
interpreter.close()
}
}The output size must match the model. A classifier with 1000 classes needs 1000 output values, while a custom model may need a different size or several output tensors. Read the model metadata when possible instead of hard-coding these assumptions.
A camera produces frames continuously, but inference may be slower than the camera. Process one frame at a time, discard stale frames, and run inference off the main UI thread. Otherwise, the preview can freeze.
iOS differences
On iOS, a Core ML model is commonly added to the Xcode project and loaded through the generated model class. Vision can handle camera buffers, resizing, and orientation. The same rules still apply: preserve the training preprocessing, avoid blocking the main thread, and reuse the loaded model.
Exercise
Exercise
A camera app shows correct predictions for saved images but poor predictions for live frames. What should you check first?
Show answer
Compare the live-frame preprocessing with training and validation preprocessing. Check orientation, RGB versus BGR order, resize and crop behavior, normalization, tensor data type, and camera buffer format.