Camera pipelines with CameraX and MediaPipe
Why it matters
- Every on-device vision feature (object detection, hand tracking, face landmarks) funnels through this CameraX-to-MediaPipe path; getting the wiring wrong causes frozen UIs or native OOM crashes that show up only on low-end devices.
- Interviewers at product companies ask you to draw the full pipeline on a whiteboard: camera buffer, format conversion, inference thread, result callback, and resource teardown. Missing any stage signals a gap.
- MediaPipe LIVE_STREAM drops frames under load by design. If your UI assumes a steady frame rate, overlays jump and users report 'laggy camera' even though the model is fast.
- The same pipeline pattern extends to MediaPipe Tasks for text and audio, and to LiteRT models you bring yourself, so the wiring knowledge transfers across the whole on-device AI module.
The simple explanation
- A restaurant kitchen: the camera is the walk-in door where raw ingredients (frames) arrive.
- The prep station (ImageAnalysis) trims and plates them in a standard format (RGBA_8888).
- The chef (MediaPipe detector) cooks one plate at a time; if the line is backed up, the host skips a plate (frame drop).
- The waiter (the result listener) brings finished dishes back to the table (UI).
- At closing time, every plate and pan must be returned to the rack (proxy.close(), detector.close()), or the next shift has nothing to work with.
The pipeline has three stages: CameraX captures frames, you convert them, and MediaPipe runs inference.
CameraX's ImageAnalysis use case delivers ImageProxy objects on a background thread you supply. Set OUTPUT_IMAGE_FORMAT_RGBA_8888 so pixel data matches what MediaPipe expects, and STRATEGY_KEEP_ONLY_LATEST so the camera never queues stale frames when inference is slow.
Turn each ImageProxy into a Bitmap (imageProxy.toBitmap(), or copy the RGBA plane into a reused bitmap as the official sample does), rotate it by imageProxy.imageInfo.rotationDegrees, and wrap it with BitmapImageBuilder(bitmap).build() to get an MPImage. Then call detector.detectAsync(mpImage, timestampMs) in LIVE_STREAM mode. The timestamp is in milliseconds and must increase every frame; the docs use SystemClock.uptimeMillis(). Results arrive through the listener you set with setResultListener on the options builder.
| Step | API | Thread |
|---|---|---|
| Capture | ImageAnalysis → ImageProxy | your Executor |
| Convert | toBitmap() → BitmapImageBuilder | same thread |
| Infer | detector.detectAsync | MediaPipe internal thread |
| Result | result listener from the options | MediaPipe callback thread |
Two rules prevent the most common bugs: always close the ImageProxy (in a finally block), and call detector.close() when the camera screen is done to free native memory. In LIVE_STREAM, MediaPipe drops a frame when it is still busy with the previous one, so your overlay must tolerate gaps. MediaPipe Tasks offer Delegate.CPU and Delegate.GPU in BaseOptions; if GPU setup fails on a device, recreate the task on CPU.
Notes
- Set
ImageAnalysisoutput format toOUTPUT_IMAGE_FORMAT_RGBA_8888; the default YUV_420_888 needs a colour conversion before you can build a bitmap. - Use
STRATEGY_KEEP_ONLY_LATESTso the camera discards queued frames instead of backing up when inference is slow. - Convert with
BitmapImageBuilder(bitmap).build(). Rotate the bitmap byimageInfo.rotationDegreesfirst, or detections come out rotated. Front cameras also need mirroring when you draw the overlay. - In LIVE_STREAM mode,
detectAsyncreturns quickly; results arrive on the listener. The timestamp (milliseconds) must strictly increase, or the call fails. - Close the proxy when you are done with it (in a
finallyblock). Forgetting it holds a camera buffer, andImageAnalysisstops delivering new frames. - Call
detector.close()when the camera screen is done (for example inViewModel.onCleared()). The detector holds native memory (model weights, GPU buffers) that the GC does not free for you. - LIVE_STREAM drops frames while the task is busy. Your UI must handle irregular result intervals; do not assume a fixed fps.
- Create the detector before the camera starts (for example while the permission prompt or preview spins up). Creating it is slow and should not happen on the main thread.
- Run all inference off the main thread.
detectAsyncin LIVE_STREAM returns quickly, butdetectin IMAGE mode is synchronous and can cause an ANR on the UI thread. - Bundle small models in
assets/; download very large models after install via Play Asset Delivery or your ownWorkManagerflow to keep the base download small.
Code example
This shows the full CameraX-to-MediaPipe LIVE_STREAM wiring: build a GPU-backed ObjectDetector (with a CPU retry), feed it rotated RGBA_8888 frames from ImageAnalysis, and tear down both resources cleanly.
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.SystemClock
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mediapipe.framework.image.BitmapImageBuilder
import com.google.mediapipe.tasks.core.BaseOptions
import com.google.mediapipe.tasks.core.Delegate
import com.google.mediapipe.tasks.vision.core.RunningMode
import com.google.mediapipe.tasks.vision.objectdetector.ObjectDetector
import com.google.mediapipe.tasks.vision.objectdetector.ObjectDetectorResult
import java.util.concurrent.ExecutorService
// 1. Build a LIVE_STREAM detector; retry on CPU if GPU setup fails
fun createDetector(
context: Context,
onResult: (ObjectDetectorResult) -> Unit
): ObjectDetector {
fun build(delegate: Delegate): ObjectDetector {
val options = ObjectDetector.ObjectDetectorOptions.builder()
.setBaseOptions(
BaseOptions.builder()
.setModelAssetPath("efficientdet_lite0.tflite")
.setDelegate(delegate)
.build()
)
.setRunningMode(RunningMode.LIVE_STREAM)
.setResultListener { result, _ -> onResult(result) } // background thread
.setErrorListener { e -> android.util.Log.e("Detector", e.message.orEmpty()) }
.build()
return ObjectDetector.createFromOptions(context, options)
}
return try { build(Delegate.GPU) } catch (e: Exception) { build(Delegate.CPU) }
}
// 2. CameraX feeds frames; convert, rotate and hand off to MediaPipe
fun attachAnalyzer(
analysis: ImageAnalysis, // built with KEEP_ONLY_LATEST + RGBA_8888
detector: ObjectDetector,
executor: ExecutorService
) {
analysis.setAnalyzer(executor) { proxy: ImageProxy ->
try {
val matrix = Matrix().apply {
postRotate(proxy.imageInfo.rotationDegrees.toFloat())
}
val raw = proxy.toBitmap()
val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, matrix, true)
val mpImage = BitmapImageBuilder(upright).build()
detector.detectAsync(mpImage, SystemClock.uptimeMillis()) // ms, increasing
} finally {
proxy.close() // return the buffer to CameraX
}
}
}
// 3. When the camera screen is done: analysis.clearAnalyzer(); detector.close(); executor.shutdown()STRATEGY_KEEP_ONLY_LATESTandOUTPUT_IMAGE_FORMAT_RGBA_8888are set on theImageAnalysis.Builder; they prevent frame-queue buildup and maketoBitmap()cheap.- The result listener runs on a MediaPipe thread, so
onResultshould write to aStateFlowor post to the main thread. toBitmap()copies the pixels, so closing the proxy infinallyright after is safe. For less garbage, the official sample reuses one bitmap and copies the plane buffer into it.
Run the idea in plain Kotlin
fun main() {
// Simulating the timestamp requirement for LIVE_STREAM
var lastTimestamp = 0L
val timestamps = mutableListOf<Long>()
// Generate 5 frames
for (i in 1..5) {
val currentTimestamp = i * 1000L // Simulating increasing time
// Check if monotonically increasing
if (currentTimestamp > lastTimestamp) {
timestamps.add(currentTimestamp)
lastTimestamp = currentTimestamp
} else {
// In real MediaPipe, this call would fail
println("Frame " + i + " rejected: timestamp not increasing")
}
}
println("Valid frames processed: " + timestamps.size)
println("Timestamps: " + timestamps.joinToString(", "))
}In production
- Crash reports showed the process being killed for memory on low-end devices after sustained camera screen use.
- The team had created a new
ObjectDetectorevery time the user rotated the screen, but never calledclose()on the old one. - Each open detector held GPU buffers and model weights in native memory that was never released.
- Moved detector creation into a
ViewModel(survives rotation) and calleddetector.close()inonCleared(). - Added a debug log of
Debug.getNativeHeapAllocatedSize()on each camera session to spot growth early. - Reproduced on a low-RAM device by rotating the phone repeatedly; confirmed the leak with
dumpsys meminfobefore and after the fix.
- Users on budget phones reported that detection boxes stopped moving after a few seconds, even though the camera preview kept updating.
- The analyzer launched a coroutine per frame that did the work later and closed the
ImageProxyonly at the end, and some error paths never closed it. - Once every camera buffer was held,
ImageAnalysisstopped delivering frames and the overlay froze on the last result.
- Converted the frame synchronously inside the analyzer, called
detectAsyncin LIVE_STREAM mode, and closed the proxy infinally. - Kept
STRATEGY_KEEP_ONLY_LATESTso the camera discards stale frames instead of queuing them. - Verified on a low-end device that the overlay updates at a variable but non-zero rate under load, and added a 'processing' indicator when the gap exceeds a threshold.
Common mistakes
- Forgetting proxy.close(). The camera buffers are limited. If you never close the proxy,
ImageAnalysisstops delivering frames. Always close it in afinallyblock, including error paths. - Not calling detector.close(). The detector holds native memory (model weights, GPU context). Call
detector.close()when the camera screen is done, or you leak native memory per camera session until the process is killed. - Wrong or duplicate timestamps. In LIVE_STREAM mode the timestamp is in milliseconds and must increase on every call. A repeated or smaller value makes the call fail. Use
SystemClock.uptimeMillis(); never pass nanoseconds or reuse a value. - Running detect() on the main thread. IMAGE-mode
detect()is synchronous and can take significant time. Calling it on the UI thread can trigger an ANR. Use LIVE_STREAM withdetectAsyncfor camera frames, or dispatch toDispatchers.Default/ a dedicated thread. - Bundling a large .tflite in the base APK. It inflates the download for every user, even those who never open the camera feature. Download the model after install via Play Asset Delivery or
WorkManager, and show a progress state until it is ready. - Assuming a fixed frame rate in LIVE_STREAM. MediaPipe drops frames while it is busy. If your overlay or animation assumes a fixed fps, it will stutter on slow devices. Design the UI to tolerate irregular result intervals and show a 'processing' state when gaps exceed a threshold.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Walk me through the CameraX to MediaPipe pipeline end to end.”
“What happens if you forget to close the ImageProxy?”
“How do you handle frame drops in LIVE_STREAM mode?”
“How do you choose between CPU and GPU for a MediaPipe task, and where does NPU fit?”
Quiz
Which ImageAnalysis backpressure strategy prevents the camera from queuing stale frames when inference is slow?
In MediaPipe LIVE_STREAM mode, what must the timestamp argument to detectAsync satisfy?
What is the consequence of not calling detector.close() in onDestroy?
Which ImageAnalysis output format makes it easiest to build an MPImage from a camera frame?
0 of 4 answered
Mini task
Wire a live object-detection overlay (15 min)
-
Add the CameraX dependencies and
com.google.mediapipe:tasks-visionto yourbuild.gradle(check the current docs for versions). Download the object detector model linked from the MediaPipe Object Detector docs intosrc/main/assets/. -
In a
FragmentorActivity, add aPreviewViewand an overlayViewto the layout. InonCreate, build anImageAnalysisuse case withOUTPUT_IMAGE_FORMAT_RGBA_8888andSTRATEGY_KEEP_ONLY_LATEST. -
Create an
ObjectDetectorwithRunningMode.LIVE_STREAMandDelegate.GPU(retry withDelegate.CPUon failure). Set a result listener that stores the latestObjectDetectorResultin aStateFlow. -
In the
ImageAnalysisanalyzer (on a single-threadExecutor), convert the proxy to a rotatedBitmap, wrap it withBitmapImageBuilder, calldetector.detectAsync(mpImage, SystemClock.uptimeMillis()), and close the proxy infinally. -
When the screen is done, call
analysis.clearAnalyzer()anddetector.close(). -
Bind the
PreviewViewto thePreviewuse case and the overlayViewto theStateFlowof detections.
Done condition: You see bounding boxes on a live camera feed. Rotate the phone 10 times and confirm the boxes still line up with objects and the overlay keeps updating. Stop the camera and confirm the detector is closed (no native memory growth in dumpsys meminfo).