Sub topic 11
Running the Model Inside an Android or iOS App
This chapter covers the app side of deployment: loading a converted model, feeding it camera frames, and getting results to the screen without freezing the interface or leaking memory. It assumes you have a converted model (for example the quantized .tflite file from the export chapter), you know why preprocessing must match training, and you can read basic Kotlin and Swift. You don't need to have shipped a mobile app before.
The shape of an on-device vision pipeline
Every app that runs a vision model repeats the same loop. A camera produces frames. Each frame is rotated, resized, and converted to the tensor layout the model expects. The runtime executes the model. Postprocessing turns the output into labels or boxes. The UI draws the result.
Three rules follow from this loop.
- Inference never runs on the main (UI) thread. A 30 ms model call is still enough to cause visible stutter when it happens during drawing.
- The pipeline drops frames instead of queuing them. If the model takes 40 ms and the camera delivers a frame every 33 ms, a queue grows without bound and the displayed result lags further behind reality.
- The model object is created once and reused. Loading a model and allocating its tensors can take hundreds of milliseconds.
Bundling the model
The model file ships inside the app package.
- Android: put
mobilenet_v2_int8.tfliteinapp/src/main/assets/. Assets are compressed by default, which prevents memory-mapping. Disable compression for the extension inbuild.gradle.ktsso the runtime can map the file directly instead of copying it onto the heap:
android {
androidResources {
noCompress += "tflite"
}
}- iOS: add the
.mlpackage(Core ML) to the target. Xcode compiles it to.mlmodelcat build time. If you use ONNX Runtime or TensorFlow Lite on iOS, add the raw file to the bundle's resources instead.
Also keep a text file or metadata entry beside the model recording its input size, channel order, normalization, and label list. Those values live in the app code otherwise, and they are the first thing to drift out of sync with the model.
Android: CameraX and the TensorFlow Lite interpreter
Add the dependencies for the interpreter, the support library (which provides FileUtil), and CameraX analysis. Check the current versions on each project's release page, because TensorFlow Lite is now distributed under the LiteRT name and the Maven coordinates have been changing.
The classifier below wraps the interpreter. It reuses its buffers across frames, so a steady-state call allocates almost nothing except the scaled bitmap.
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import org.tensorflow.lite.Interpreter
import org.tensorflow.lite.support.common.FileUtil
import java.nio.ByteBuffer
import java.nio.ByteOrder
class Classifier(context: Context) : AutoCloseable {
private val size = 224
private val interpreter: Interpreter
private val input: ByteBuffer =
ByteBuffer.allocateDirect(size * size * 3).order(ByteOrder.nativeOrder())
private val pixels = IntArray(size * size)
private val output = Array(1) { ByteArray(1000) }
init {
val model = FileUtil.loadMappedFile(context, "mobilenet_v2_int8.tflite")
interpreter = Interpreter(model, Interpreter.Options().setNumThreads(4))
}
// Returns the index of the highest-scoring class.
fun classify(frame: Bitmap, rotationDegrees: Int): Int {
val matrix = Matrix().apply { postRotate(rotationDegrees.toFloat()) }
val upright = Bitmap.createBitmap(frame, 0, 0, frame.width, frame.height, matrix, true)
val scaled = Bitmap.createScaledBitmap(upright, size, size, true)
scaled.getPixels(pixels, 0, size, 0, 0, size, size)
input.rewind()
for (p in pixels) {
input.put(((p shr 16) and 0xFF).toByte()) // R
input.put(((p shr 8) and 0xFF).toByte()) // G
input.put((p and 0xFF).toByte()) // B
}
input.rewind()
interpreter.run(input, output)
return output[0].indices.maxByOrNull { output[0][it].toInt() and 0xFF } ?: -1
}
override fun close() = interpreter.close()
}Notes on this code:
ByteBuffer.allocateDirectwith native byte order avoids a copy between the JVM heap and native memory.- Output bytes are signed in Kotlin. Mask with
and 0xFFbefore comparing, or classes with scores above 127 will rank below those with low scores. - Writing raw 0–255 bytes is correct only if the model's input quantization maps them to the values it saw during calibration. Check the input's scale and zero point (the Python
get_input_details()call shows them underquantization). For a model calibrated on[-1, 1]data, a scale near 0.0078 and zero point near 128 mean raw pixel bytes are already right. Other values mean the app must apply the preprocessing itself. Bitmap.createScaledBitmapstretches the image. If training used a center crop, stretching changes the aspect ratio and costs accuracy. Match whatever the training pipeline did.
Wire the classifier to the camera with ImageAnalysis. The key settings are the backpressure strategy and the explicit close():
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import java.util.concurrent.Executors
val analysisExecutor = Executors.newSingleThreadExecutor()
val analysis = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888)
.build()
analysis.setAnalyzer(analysisExecutor) { image: ImageProxy ->
try {
val bitmap = image.toBitmap()
val classIndex = classifier.classify(bitmap, image.imageInfo.rotationDegrees)
// Post classIndex to the UI thread here, for example with a StateFlow.
} finally {
image.close() // CameraX delivers no new frame until this runs
}
}STRATEGY_KEEP_ONLY_LATEST implements the drop-frames rule. rotationDegrees tells you how far the sensor image is rotated from upright. Ignoring it is the most common cause of a model that works on test photos but fails live, because the phone's sensor is usually mounted sideways. Request RGBA output so CameraX does the YUV-to-RGB conversion. ImageProxy.toBitmap() needs a recent CameraX release.
iOS: Core ML through Vision
On iOS the least error-prone route for image models is the Vision framework wrapping a Core ML model. VNCoreMLRequest handles resizing, cropping, and pixel format, and VNImageRequestHandler takes an orientation argument.
import CoreML
import Vision
final class Classifier {
private let request: VNCoreMLRequest
private let queue = DispatchQueue(label: "inference", qos: .userInitiated)
init() throws {
let config = MLModelConfiguration()
config.computeUnits = .all // let Core ML choose CPU, GPU or Neural Engine
guard let url = Bundle.main.url(forResource: "MobileNetV2", withExtension: "mlmodelc") else {
fatalError("Model missing from bundle")
}
let mlModel = try MLModel(contentsOf: url, configuration: config)
let visionModel = try VNCoreMLModel(for: mlModel)
request = VNCoreMLRequest(model: visionModel)
request.imageCropAndScaleOption = .centerCrop // match training
}
func classify(_ pixelBuffer: CVPixelBuffer,
orientation: CGImagePropertyOrientation,
completion: @escaping (String?, Float) -> Void) {
queue.async {
let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer,
orientation: orientation,
options: [:])
do {
try handler.perform([self.request])
let top = (self.request.results as? [VNClassificationObservation])?.first
DispatchQueue.main.async { completion(top?.identifier, top?.confidence ?? 0) }
} catch {
DispatchQueue.main.async { completion(nil, 0) }
}
}
}
}Feed it from an AVCaptureVideoDataOutput and set alwaysDiscardsLateVideoFrames = true. That is the iOS equivalent of KEEP_ONLY_LATEST. Use the same pixel buffer in the delegate callback without copying it, and do not hold on to buffers after the call returns, because the capture pipeline recycles them. The Vision request object may be reused, but call it from one queue at a time.
Platform comparison
| Concern | Android (TFLite/LiteRT) | iOS (Core ML + Vision) |
|---|---|---|
| Camera API | CameraX `ImageAnalysis` | `AVCaptureVideoDataOutput` |
| Drop late frames | `STRATEGY_KEEP_ONLY_LATEST` | `alwaysDiscardsLateVideoFrames` |
| Orientation | `rotationDegrees`, applied by you | `CGImagePropertyOrientation` passed to Vision |
| Resize and crop | Your code | `imageCropAndScaleOption` |
| Accelerator choice | Delegate set in options | `computeUnits` |
| Resource cleanup | Call `close()` on interpreter and frame | Automatic reference counting |
Common failures in the app layer
- Wrong results only on the live camera. Check rotation first, then channel order (BGR vs RGB), then crop vs stretch. Save one preprocessed frame to disk and look at it.
- Slow first frame. Model load, tensor allocation, and accelerator compilation happen on first use. Create the classifier at startup, run one dummy inference, and only then enable the camera UI.
- Growing memory or a frozen camera on Android. An
ImageProxythat is never closed stalls the stream. AnInterpreterthat is never closed leaks native memory. Close both, including on exception paths. - Crashes on some devices only. An accelerator may be missing or rejected at runtime. Wrap accelerator setup so a failure falls back to CPU rather than crashing, and log which path was chosen.
- UI stutter despite a fast model. Bitmap allocation and conversion often cost more than inference. Reuse buffers and measure each stage separately.
Exercise
Your Android app classifies still photos from the gallery correctly, but live camera frames give wrong labels. The model and classifier code are identical in both cases. Name two likely causes and one way to check each.
Show answer
Likely causes: (1) The live frame is not rotated upright. CameraX frames come in sensor orientation, so the app must apply imageInfo.rotationDegrees. Check by saving the bitmap that is passed to the interpreter and looking at whether it is sideways. (2) The color format or channel order differs, for example a YUV frame converted wrongly or BGR bytes written where RGB is expected. Check by saving the preprocessed image and comparing its colors with a gallery photo, or by comparing the first few input bytes of the same scene from both sources. Other acceptable causes: stretching instead of cropping, or the frame not being closed so stale frames are analyzed.
Exercise
Why should the analyzer drop frames while the model is busy instead of queuing them, and which setting does this on Android and iOS?
Show answer
A queue grows whenever inference is slower than the camera frame rate, so results appear further behind reality and memory use rises. Dropping frames keeps the result tied to the most recent image. On Android use ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST. On iOS set alwaysDiscardsLateVideoFrames = true on AVCaptureVideoDataOutput.