Real-time object detection camera app with MediaPipe
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 layer | Responsibility |
|---|---|
| Camera layer | CameraX Preview and ImageAnalysis use cases; STRATEGY_KEEP_ONLY_LATEST, RGBA_8888 output; permission gating. |
| Detection layer | MediaPipe ObjectDetector in LIVE_STREAM mode; BaseOptions with model asset path and delegate; result and error listeners. |
| Overlay layer | Compose Canvas that draws boxes and labels; maps upright-image coordinates to overlay pixels with scale and crop offset. |
| State layer | DetectionViewModel holding the detector; StateFlow<DetectionFrame?> as the single source of truth for the UI. |
| Settings layer | DataStore-backed SettingsRepository for score threshold, max results, and CPU/GPU delegate choice. |
| Lifecycle layer | Permission 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.
- Add the CameraX
camera-core,camera-camera2,camera-lifecycle, andcamera-viewdependencies in the modulebuild.gradle.kts. - Create a
CameraXPreviewcomposable that wraps aPreviewViewinAndroidViewand binds aPreviewuse case to the back camera withProcessCameraProvider.bindToLifecycle. - Request the
CAMERApermission at runtime withrememberLauncherForActivityResult; show a permission-denied state with a retry action when the user declines. - Bind with the screen's
LifecycleOwnerso CameraX stops the camera when the lifecycle stops; unbind inDisposableEffectwhen the composable leaves composition. - 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.
- Add the
com.google.mediapipe:tasks-visiondependency and place a.tfliteobject detection model insrc/main/assets. - Build the
ObjectDetectorwithBaseOptions.setModelAssetPath,RunningMode.LIVE_STREAM,setResultListener, andsetErrorListeneron the options builder. - Configure
ImageAnalysiswithsetBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)andsetOutputImageFormat(ImageAnalysis.OUTPUT_IMAGE_FORMAT_RGBA_8888), and give it a single-thread executor. - Create a
DetectionAnalyzerthat rotates each frame upright, builds anMPImagewithBitmapImageBuilder, callsdetectAsyncwith a strictly increasingSystemClock.uptimeMillis()timestamp, and closes the proxy in all cases. - 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.
- Create a
DetectionOverlaycomposable that takes the latestDetectionFrame. - Inside
Canvas, draw eachboundingBox()withdrawRect, and draw the top category'scategoryName()andscore()withdrawTextand aTextMeasurer. - Map coordinates: boxes are in pixels of the upright image you passed in. With the default
PreviewViewscale type (fill center), usescale = max(canvasWidth / imageWidth, canvasHeight / imageHeight)and subtract half the overflow on each axis as an offset. - Expose the frame through a
StateFlowinDetectionViewModeland collect it in the screen withcollectAsStateWithLifecycle. - 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.
- Add a
SettingsRepositorybacked by DataStore storingscoreThreshold,maxResults, anddelegate(CPU or GPU). - Build a settings sheet with sliders and a toggle; write changes back to DataStore.
- In
DetectionViewModel, observe settings; on change, build a new detector off the main thread, swap it into the analyzer, then close the old one. - Wrap creation with
Delegate.GPUintry/catch; on failure, log the error and build again withDelegate.CPU. - 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.
- Close every
ImageProxyin the analyzer withuseortry/finally, including the early return for a repeated timestamp. - When the screen or ViewModel is done, call
analysis.clearAnalyzer()first, thendetector.close(), then shut down the analysis executor. - Compute inference time inside the result listener as
SystemClock.uptimeMillis() - result.timestampMs();detectAsyncreturns immediately, so timing around that call measures nothing. - Display the inference time in milliseconds as a small label in a corner of the overlay.
- 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.
- Never hard-code a rotation: read
imageInfo.rotationDegreesfor every frame and rotate the bitmap before detection, so boxes always refer to the upright image. - Update
ImageAnalysis.targetRotationwhen the display rotation changes, and let the Canvas use its currentsizeon every draw instead of a cached size. - 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.
- Keep
DetectionFrameimmutable and pass it as a single state value so the overlay redraws without extra recomposition. - 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_STREAMresults.detectAsyncreturns nothing and runs on its own, and the listener fires on a background thread, so write results to aStateFlowinstead of touching the UI directly. - Timestamps are in milliseconds and must strictly increase.
lastTimestampMsskips a frame that lands in the same millisecond, andusestill closes the proxy on that early return. - Rotating the bitmap by
rotationDegreesbefore detection meansboundingBox()comes back in upright-image pixels. The listener'sinputgives that image's width and height for the overlay mapping. ObjectDetectorResultis a Java value class, so read it with method calls:result.detections(),detection.boundingBox(),detection.categories(),category.categoryName(),category.score().setModelAssetPathreads fromassets/; for a model you download at runtime, pass a directByteBufferwithsetModelAssetBufferinstead.
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 missedclose()freezes analysis. Fix: wrap the analyzer body inuseortry/finally. - Timestamps that do not strictly increase. MediaPipe rejects a
LIVE_STREAMframe whose timestamp is not greater than the previous one, and the error stops results arriving. Fix: use a monotonic clock such asSystemClock.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.rotationDegreeson every frame, never a hard-coded angle. - No fallback when the GPU delegate fails. Some devices cannot create the GPU delegate and
createFromOptionsthrows. Fix: catch the failure, log it, and build again withDelegate.CPU. - Closing the detector while frames are still in flight. If you call
detector.close()while the analyzer is still running, the nextdetectAsynccall throws on a closed detector. Fix: callanalysis.clearAnalyzer()first, then close the detector, then shut down the executor.
Code review finding
- 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
PreviewViewfills the view by scaling uniformly and cropping the overflow.
- Compute the mapping inside the Canvas draw block from the current
sizeand theimageWidthandimageHeightcarried in eachDetectionFrame. - Rotate each frame by
imageInfo.rotationDegreesbefore detection, and updateImageAnalysis.targetRotationwhen the display rotation changes. - Match the
PreviewViewfill-center rule: one uniform scale,max(canvasWidth / imageWidth, canvasHeight / imageHeight), plus an offset of half the cropped overflow on each axis.
Stretch goals
- Swap
ObjectDetectorforHandLandmarkerand 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
setModelAssetBufferwithout 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.
ImageAnalysisusesSTRATEGY_KEEP_ONLY_LATESTandOUTPUT_IMAGE_FORMAT_RGBA_8888.- The
ObjectDetectorruns inLIVE_STREAMmode with the result listener set on the options builder anddetectAsynccalled 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
ImageProxyis 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_STREAMoverIMAGEorVIDEOmode: 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
StateFlowon the main thread. Explain why theStateFlowis 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.