Real-time object detection camera app with MediaPipe

Build a real-time object detection camera app with Jetpack Compose, CameraX ImageAnalysis, and MediaPipe Tasks Vision running a TFLite model on-device. About 28 hours.

What you will build

The finished app opens the device camera, runs an on-device .tflite object detector on the camera frames, and draws bounding boxes with class labels and confidence scores on a Compose Canvas overlay. You wire CameraX ImageAnalysis (STRATEGY_KEEP_ONLY_LATEST, OUTPUT_IMAGE_FORMAT_RGBA_8888) into a MediaPipe ObjectDetector in LIVE_STREAM mode, map box coordinates to the preview, and show the inference time for each result. Settings let the user adjust the score threshold, max results, and choose the GPU or CPU delegate, with a CPU fallback. Every ImageProxy is closed, and the detector is closed when the screen goes away.

This project proves you can build a real-time vision pipeline in Kotlin: you handle camera permissions, off-main-thread model loading, rotation-aware coordinate mapping, background-thread callbacks, and resource cleanup. It shows an employer you understand the full path from sensor to pixels on screen without a cloud round-trip.

Skills you practise

  • CameraX Preview and ImageAnalysis in Compose
  • MediaPipe Tasks Vision ObjectDetector in LIVE_STREAM mode
  • Compose Canvas overlay with coordinate mapping
  • Threading, lifecycle and resource cleanup
  • CPU/GPU delegate selection with fallback
  • DataStore-backed settings and StateFlow UI state
  • Rotation-aware bounding-box drawing

Architecture

The app has a single CameraDetectionScreen composable that hosts a CameraXPreview (an AndroidView wrapping a PreviewView) and a DetectionOverlay Canvas layered on top. A DetectionViewModel owns the ObjectDetector and exposes a StateFlow<DetectionFrame?> carrying the latest ObjectDetectorResult, the size of the image the boxes refer to, and the inference time.

Data flow: CameraX delivers frames through ImageAnalysis with STRATEGY_KEEP_ONLY_LATEST and RGBA_8888 output, on a single background executor. A DetectionAnalyzer converts each ImageProxy to a Bitmap with toBitmap(), rotates it upright using imageInfo.rotationDegrees, wraps it in an MPImage with BitmapImageBuilder, calls detectAsync(mpImage, timestampMs) with a strictly increasing millisecond timestamp, and closes the proxy. In LIVE_STREAM mode, results arrive asynchronously on a background thread through the result listener set on the options builder; errors arrive through the error listener. The listener wraps each result in a DetectionFrame and writes it to the StateFlow.

The Compose layer collects the flow and redraws the Canvas, mapping image-pixel boxes to overlay pixels using the same scaling rule as the PreviewView. A SettingsRepository backed by DataStore holds threshold, max results, and delegate choice. On a settings change, the ViewModel builds a new detector off the main thread and closes the old one. When the screen is done, the analyzer is cleared first, then the detector is closed.

Module or layerResponsibility
Camera layerCameraX Preview and ImageAnalysis use cases; STRATEGY_KEEP_ONLY_LATEST, RGBA_8888 output; permission gating.
Detection layerMediaPipe ObjectDetector in LIVE_STREAM mode; BaseOptions with model asset path and delegate; result and error listeners.
Overlay layerCompose Canvas that draws boxes and labels; maps upright-image coordinates to overlay pixels with scale and crop offset.
State layerDetectionViewModel holding the detector; StateFlow<DetectionFrame?> as the single source of truth for the UI.
Settings layerDataStore-backed SettingsRepository for score threshold, max results, and CPU/GPU delegate choice.
Lifecycle layerPermission flow, ImageProxy and detector cleanup, rotation handling, off-main-thread setup.

Milestones

1. CameraX preview in Compose

Show a live camera feed inside a Jetpack Compose screen with runtime permission handling.

  1. Add the CameraX camera-core, camera-camera2, camera-lifecycle, and camera-view dependencies in the module build.gradle.kts.
  2. Create a CameraXPreview composable that wraps a PreviewView in AndroidView and binds a Preview use case to the back camera with ProcessCameraProvider.bindToLifecycle.
  3. Request the CAMERA permission at runtime with rememberLauncherForActivityResult; show a permission-denied state with a retry action when the user declines.
  4. Bind with the screen's LifecycleOwner so CameraX stops the camera when the lifecycle stops; unbind in DisposableEffect when the composable leaves composition.
  5. Verify the preview fills the screen and keeps working after rotation.

Done when: The app requests camera permission, shows a live back-camera preview in Compose, and handles the denied case with a message.

Lessons: runtime permissions, side effects launchedeffect and friends, camera pipelines with camerax and mediapipe

2. ImageAnalysis pipeline with MediaPipe ObjectDetector

Feed camera frames into a MediaPipe ObjectDetector in LIVE_STREAM mode and receive detection results.

  1. Add the com.google.mediapipe:tasks-vision dependency and place a .tflite object detection model in src/main/assets.
  2. Build the ObjectDetector with BaseOptions.setModelAssetPath, RunningMode.LIVE_STREAM, setResultListener, and setErrorListener on the options builder.
  3. Configure ImageAnalysis with setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) and setOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888), and give it a single-thread executor.
  4. Create a DetectionAnalyzer that rotates each frame upright, builds an MPImage with BitmapImageBuilder, calls detectAsync with a strictly increasing SystemClock.uptimeMillis() timestamp, and closes the proxy in all cases.
  5. Create the detector off the main thread (for example with withContext(Dispatchers.Default)) and log the first results in Logcat.

Done when: Logcat shows detection results (category names and scores) arriving from the result listener while the camera is live.

Lessons: mediapipe tasks vision text and audio, camera pipelines with camerax and mediapipe, dispatchers and threading

3. Canvas overlay with bounding boxes and labels

Draw detection boxes and text labels on a Compose Canvas that overlays the camera preview.

  1. Create a DetectionOverlay composable that takes the latest DetectionFrame.
  2. Inside Canvas, draw each boundingBox() with drawRect, and draw the top category's categoryName() and score() with drawText and a TextMeasurer.
  3. Map coordinates: boxes are in pixels of the upright image you passed in. With the default PreviewView scale type (fill center), use scale = max(canvasWidth / imageWidth, canvasHeight / imageHeight) and subtract half the overflow on each axis as an offset.
  4. Expose the frame through a StateFlow in DetectionViewModel and collect it in the screen with collectAsStateWithLifecycle.
  5. Point the camera at everyday objects and confirm the boxes line up with them.

Done when: Bounding boxes and labels appear on the preview, follow objects in real time, and line up in portrait.

Lessons: composables and modifiers, custom layouts and modifiers, unidirectional data flow

4. Settings, delegate switch, and fallback

Let the user adjust score threshold, max results, and CPU/GPU delegate; fall back to CPU when the GPU delegate cannot be created.

  1. Add a SettingsRepository backed by DataStore storing scoreThreshold, maxResults, and delegate (CPU or GPU).
  2. Build a settings sheet with sliders and a toggle; write changes back to DataStore.
  3. In DetectionViewModel, observe settings; on change, build a new detector off the main thread, swap it into the analyzer, then close the old one.
  4. Wrap creation with Delegate.GPU in try/catch; on failure, log the error and build again with Delegate.CPU.
  5. Show a small status text in the UI with the delegate that is actually active.

Done when: Changing the threshold or max results changes the overlay within a moment; choosing GPU on a device where it fails falls back to CPU without crashing.

Lessons: stateflow and sharedflow, gpu and npu acceleration, viewmodel and ui state

5. Lifecycle, cleanup, and inference time

Close every ImageProxy and the detector at the right moments, and display the inference time for each result.

  1. Close every ImageProxy in the analyzer with use or try/finally, including the early return for a repeated timestamp.
  2. When the screen or ViewModel is done, call analysis.clearAnalyzer() first, then detector.close(), then shut down the analysis executor.
  3. Compute inference time inside the result listener as SystemClock.uptimeMillis() - result.timestampMs(); detectAsync returns immediately, so timing around that call measures nothing.
  4. Display the inference time in milliseconds as a small label in a corner of the overlay.
  5. Run LeakCanary in a debug build, navigate in and out of the camera screen, and confirm no retained ViewModel or Activity and no crash.

Done when: LeakCanary reports no leaks after navigating away; the inference time updates as results arrive; rapid navigation does not crash with a closed-detector error.

Lessons: memory leaks and leakcanary, jank frames and perfetto, structured concurrency and cancellation

6. Rotation, error states, and polish

Handle device rotation correctly, show error and loading states, and keep the overlay smooth.

  1. Never hard-code a rotation: read imageInfo.rotationDegrees for every frame and rotate the bitmap before detection, so boxes always refer to the upright image.
  2. Update ImageAnalysis.targetRotation when the display rotation changes, and let the Canvas use its current size on every draw instead of a cached size.
  3. Show a loading state while the detector is being created and an error state if the model file fails to load or the error listener fires.
  4. Keep DetectionFrame immutable and pass it as a single state value so the overlay redraws without extra recomposition.
  5. Test in portrait, landscape, and split-screen; confirm boxes stay aligned with objects.

Done when: Boxes align after rotation and in split-screen; loading and error states are visible; the overlay stays smooth while objects move.

Lessons: single source of truth, latency cost and fallbacks, performance monitoring in production

Key code

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.os.SystemClock
import android.util.Log
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
 
data class DetectionFrame(
    val result: ObjectDetectorResult,
    val imageWidth: Int,   // size of the upright image the boxes refer to
    val imageHeight: Int,
    val inferenceMs: Long,
)
 
// Build a LIVE_STREAM detector; fall back to CPU if the GPU delegate fails
fun buildDetector(
    context: Context,
    preferGpu: Boolean,
    threshold: Float,
    maxResults: Int,
    onFrame: (DetectionFrame) -> Unit,
): Pair<ObjectDetector, Delegate> {
    fun build(delegate: Delegate): ObjectDetector {
        val options = ObjectDetector.ObjectDetectorOptions.builder()
            .setBaseOptions(
                BaseOptions.builder()
                    .setModelAssetPath("detector.tflite") // src/main/assets
                    .setDelegate(delegate)
                    .build()
            )
            .setRunningMode(RunningMode.LIVE_STREAM)
            .setScoreThreshold(threshold)
            .setMaxResults(maxResults)
            .setResultListener { result, input -> // background thread
                val inferenceMs = SystemClock.uptimeMillis() - result.timestampMs()
                onFrame(DetectionFrame(result, input.width, input.height, inferenceMs))
            }
            .setErrorListener { e -> Log.e("Detector", e.message.orEmpty()) }
            .build()
        return ObjectDetector.createFromOptions(context, options)
    }
    if (preferGpu) {
        try {
            return build(Delegate.GPU) to Delegate.GPU
        } catch (e: Exception) {
            Log.w("Detector", "GPU delegate failed, using CPU", e)
        }
    }
    return build(Delegate.CPU) to Delegate.CPU
}
 
class DetectionAnalyzer(private val detector: ObjectDetector) : ImageAnalysis.Analyzer {
    private var lastTimestampMs = 0L
 
    override fun analyze(image: ImageProxy) {
        image.use { proxy -> // closes the proxy on every path
            val now = SystemClock.uptimeMillis()
            if (now <= lastTimestampMs) return // timestamps must strictly increase
            lastTimestampMs = now
 
            val rotate = Matrix().apply { postRotate(proxy.imageInfo.rotationDegrees.toFloat()) }
            val raw = proxy.toBitmap() // cheap with RGBA_8888 output
            val upright = Bitmap.createBitmap(raw, 0, 0, raw.width, raw.height, rotate, true)
            detector.detectAsync(BitmapImageBuilder(upright).build(), now)
        }
    }
}
  • The result listener is set on the options builder; it is the only way to receive LIVE_STREAM results. detectAsync returns nothing and runs on its own, and the listener fires on a background thread, so write results to a StateFlow instead of touching the UI directly.
  • Timestamps are in milliseconds and must strictly increase. lastTimestampMs skips a frame that lands in the same millisecond, and use still closes the proxy on that early return.
  • Rotating the bitmap by rotationDegrees before detection means boundingBox() comes back in upright-image pixels. The listener's input gives that image's width and height for the overlay mapping.
  • ObjectDetectorResult is a Java value class, so read it with method calls: result.detections(), detection.boundingBox(), detection.categories(), category.categoryName(), category.score().
  • setModelAssetPath reads from assets/; for a model you download at runtime, pass a direct ByteBuffer with setModelAssetBuffer instead.

Pitfalls

  • Not closing ImageProxy on every code path. With STRATEGY_KEEP_ONLY_LATEST, CameraX will not deliver another frame until the current proxy is closed, so one missed close() freezes analysis. Fix: wrap the analyzer body in use or try/finally.
  • Timestamps that do not strictly increase. MediaPipe rejects a LIVE_STREAM frame whose timestamp is not greater than the previous one, and the error stops results arriving. Fix: use a monotonic clock such as SystemClock.uptimeMillis() and skip a frame when the value has not moved past the last one.
  • Creating the ObjectDetector on the main thread. Loading the model and initialising the GPU delegate can take long enough to freeze the UI or cause an ANR. Fix: build the detector on a background dispatcher and publish the ready instance to the analyzer.
  • Ignoring rotation. Camera frames usually arrive rotated relative to the screen, and the rotation changes with the device. Without correcting it, the model sees sideways images and boxes land in the wrong place. Fix: rotate by imageInfo.rotationDegrees on every frame, never a hard-coded angle.
  • No fallback when the GPU delegate fails. Some devices cannot create the GPU delegate and createFromOptions throws. Fix: catch the failure, log it, and build again with Delegate.CPU.
  • Closing the detector while frames are still in flight. If you call detector.close() while the analyzer is still running, the next detectAsync call throws on a closed detector. Fix: call analysis.clearAnalyzer() first, then close the detector, then shut down the executor.

Code review finding

Bounding boxes drift after screen rotation
  • The overlay mapping was computed once from the first preview size and cached, so it is wrong after the device rotates or enters split-screen.
  • The analyzer uses a hard-coded 90 degree rotation instead of imageInfo.rotationDegrees, so frames are wrong in landscape and on devices with a different sensor orientation.
  • The mapping scales boxes with separate x and y ratios, ignoring that PreviewView fills the view by scaling uniformly and cropping the overflow.
The fix
  • Compute the mapping inside the Canvas draw block from the current size and the imageWidth and imageHeight carried in each DetectionFrame.
  • Rotate each frame by imageInfo.rotationDegrees before detection, and update ImageAnalysis.targetRotation when the display rotation changes.
  • Match the PreviewView fill-center rule: one uniform scale, max(canvasWidth / imageWidth, canvasHeight / imageHeight), plus an offset of half the cropped overflow on each axis.

Stretch goals

  • Swap ObjectDetector for HandLandmarker and draw the hand landmarks with a skeleton overlay.
  • Add ML Kit object detection as a fallback path when the MediaPipe model file is missing or fails to load.
  • Download a model at runtime, cache it in app storage, and rebuild the detector with setModelAssetBuffer without restarting the app.
  • Add a capture button that saves the current frame with the boxes drawn onto the bitmap.
  • Bundle two models (a small fast one and a larger, more accurate one), let the user switch between them, and compare inference time and results on your own devices.

Done checklist

  • Camera permission is requested at runtime and the denied state shows a clear message with a retry action.
  • ImageAnalysis uses STRATEGY_KEEP_ONLY_LATEST and OUTPUT_IMAGE_FORMAT_RGBA_8888.
  • The ObjectDetector runs in LIVE_STREAM mode with the result listener set on the options builder and detectAsync called with strictly increasing millisecond timestamps.
  • The detector is created off the main thread; on teardown the analyzer is cleared before the detector is closed.
  • Every ImageProxy is closed on all code paths, including the skipped-frame early return.
  • Bounding boxes align with objects in portrait, landscape, and split-screen.
  • GPU delegate failure falls back to CPU without crashing; the active delegate is shown in the UI.
  • Inference time is displayed and updates as results arrive.

Talking about it in an interview

  • Explain why you chose LIVE_STREAM over IMAGE or VIDEO mode: it runs detection asynchronously and delivers results through a listener, so the camera thread never blocks waiting for inference, and frames that arrive while the detector is busy can be dropped instead of piling up.
  • Discuss the CPU vs GPU delegate trade-off: the GPU is often faster but not available or stable everywhere; the fallback keeps the app working on every device. Mention how you would compare them with real measurements on low-end and high-end devices, for example with Perfetto traces.
  • Describe the coordinate-mapping problem: the detector returns boxes in the pixels of the image you gave it, the preview has a different size and aspect ratio, and the camera adds a rotation. Walk through rotate first, then one uniform scale plus a crop offset, recomputed on every draw.
  • Talk about threading: the analyzer runs on a CameraX executor, the result listener fires on a MediaPipe background thread, and the UI collects a StateFlow on the main thread. Explain why the StateFlow is the hand-off point.
  • Mention what you would change for production: remote model updates with a versioned model file, testing two models behind a feature flag, and telemetry for inference time per device tier to catch regressions.