12-camera-mlkit.md
.codex/skills/compose-kotlin-agent-skills/references/12-camera-mlkit.md
1# Camera & ML Kit — CameraX, Pose Detection, Angle Calculation23## Contents45- CameraX setup with Compose6- ML Kit pose detection7- Angle calculation from landmarks8- 1€ filter for smoothing9- 2D projection vs 3D angles10- Production patterns from RepLock1112## CameraX Setup with Compose1314```kotlin15@Composable16fun CameraPreview(17 modifier: Modifier = Modifier,18 onPoseDetected: (Pose) -> Unit19) {20 val context = LocalContext.current21 val lifecycleOwner = LocalLifecycleOwner.current2223 val previewView = remember { PreviewView(context) }2425 LaunchedEffect(Unit) {26 val cameraProvider = ProcessCameraProvider.getInstance(context).await()2728 val preview = Preview.Builder().build().also {29 it.surfaceProvider = previewView.surfaceProvider30 }3132 val imageAnalysis = ImageAnalysis.Builder()33 .setTargetResolution(Size(640, 480))34 .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)35 .build()36 .also { analysis ->37 analysis.setAnalyzer(38 MoreExecutors.directExecutor(),39 PoseAnalyzer(onPoseDetected)40 )41 }4243 val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA4445 cameraProvider.unbindAll()46 cameraProvider.bindToLifecycle(47 lifecycleOwner,48 cameraSelector,49 preview,50 imageAnalysis51 )52 }5354 AndroidView(55 factory = { previewView },56 modifier = modifier57 )58}59```6061```toml62[dependencies]63camerax-core = { module = "androidx.camera:camera-core", version.ref = "camerax" }64camerax-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camerax" }65camerax-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = "camerax" }66camerax-view = { module = "androidx.camera:camera-view", version.ref = "camerax" }67mlkit-pose = { module = "com.google.mlkit:pose-detection", version = "18.0.0-beta5" }68```6970### Key CameraX Rules71721. **Bind to lifecycle** — CameraX auto-starts/stops with lifecycle owner732. **`STRATEGY_KEEP_ONLY_LATEST`** — drops frames if analyzer is slow. Essential for ML Kit743. **`unbindAll()` before binding** — prevents duplicate use case errors754. **Resolution 640x480** — sufficient for pose detection, saves battery765. **Front camera for workouts** — user faces the screen7778## ML Kit Pose Detection7980### Pose Analyzer8182```kotlin83class PoseAnalyzer(84 private val onPoseDetected: (Pose) -> Unit85) : ImageAnalysis.Analyzer {8687 private val poseDetector = PoseDetection.getClient(88 PoseDetectorOptions.Builder()89 .setDetectorMode(PoseDetectorOptions.STREAM_MODE)90 .build()91 )9293 @androidx.camera.core.ExperimentalGetImage94 override fun analyze(imageProxy: ImageProxy) {95 val mediaImage = imageProxy.image ?: run {96 imageProxy.close()97 return98 }99100 val inputImage = InputImage.fromMediaImage(101 mediaImage,102 imageProxy.imageInfo.rotationDegrees103 )104105 poseDetector.process(inputImage)106 .addOnSuccessListener { pose ->107 onPoseDetected(pose)108 }109 .addOnCompleteListener {110 imageProxy.close() // ALWAYS close — blocks next frame otherwise111 }112 }113}114```115116**Critical:** always close `ImageProxy` in `addOnCompleteListener`, not `addOnSuccessListener`. If detection fails, proxy must still close.117118### STREAM_MODE vs SINGLE_IMAGE_MODE119120| Mode | Use for | FPS |121|------|---------|-----|122| `STREAM_MODE` | Real-time rep counting | ~15-30fps |123| `SINGLE_IMAGE_MODE` | Single photo analysis | N/A |124125Always STREAM_MODE for workout tracking.126127## Angle Calculation from Landmarks128129### 2D Angle Between Three Points130131```kotlin132fun calculateAngle(133 first: PoseLandmark, // e.g., shoulder134 middle: PoseLandmark, // e.g., elbow (vertex)135 last: PoseLandmark // e.g., wrist136): Float {137 val dx1 = first.position.x - middle.position.x138 val dy1 = first.position.y - middle.position.y139 val dx2 = last.position.x - middle.position.x140 val dy2 = last.position.y - middle.position.y141142 val angle = atan2(dy2, dx2) - atan2(dy1, dx1)143 var degrees = Math.toDegrees(angle.toDouble()).toFloat()144145 if (degrees < 0) degrees += 360f146 if (degrees > 180) degrees = 360f - degrees147148 return degrees // 0-180 range149}150```151152### Pushup Detection State Machine153154```kotlin155enum class PushupPhase { UP, DOWN }156157class PushupRepCounter {158 private var phase = PushupPhase.UP159 private var repCount = 0160 private val elbowAngleFilter = OneEuroFilter(frequency = 15.0)161162 fun onPoseUpdate(pose: Pose): Int {163 val leftShoulder = pose.getPoseLandmark(PoseLandmark.LEFT_SHOULDER) ?: return repCount164 val leftElbow = pose.getPoseLandmark(PoseLandmark.LEFT_ELBOW) ?: return repCount165 val leftWrist = pose.getPoseLandmark(PoseLandmark.LEFT_WRIST) ?: return repCount166167 val rawAngle = calculateAngle(leftShoulder, leftElbow, leftWrist)168 val smoothedAngle = elbowAngleFilter.filter(rawAngle.toDouble()).toFloat()169170 when (phase) {171 PushupPhase.UP -> {172 if (smoothedAngle < 90f) { // arms bent = down position173 phase = PushupPhase.DOWN174 }175 }176 PushupPhase.DOWN -> {177 if (smoothedAngle > 150f) { // arms extended = up position178 phase = PushupPhase.UP179 repCount++180 }181 }182 }183184 return repCount185 }186}187```188189### Squat Detection190191```kotlin192class SquatRepCounter {193 private var phase = SquatPhase.STANDING194 private var repCount = 0195 private val kneeAngleFilter = OneEuroFilter(frequency = 15.0)196197 fun onPoseUpdate(pose: Pose): Int {198 val hip = pose.getPoseLandmark(PoseLandmark.LEFT_HIP) ?: return repCount199 val knee = pose.getPoseLandmark(PoseLandmark.LEFT_KNEE) ?: return repCount200 val ankle = pose.getPoseLandmark(PoseLandmark.LEFT_ANKLE) ?: return repCount201202 val rawAngle = calculateAngle(hip, knee, ankle)203 val smoothed = kneeAngleFilter.filter(rawAngle.toDouble()).toFloat()204205 when (phase) {206 SquatPhase.STANDING -> {207 if (smoothed < 110f) phase = SquatPhase.DOWN208 }209 SquatPhase.DOWN -> {210 if (smoothed > 160f) {211 phase = SquatPhase.STANDING212 repCount++213 }214 }215 }216 return repCount217 }218}219```220221## 1€ Filter for Landmark Smoothing222223ML Kit landmarks jitter frame-to-frame. 1€ filter smooths while keeping responsiveness.224225```kotlin226class OneEuroFilter(227 private val frequency: Double = 15.0,228 private val minCutoff: Double = 1.0,229 private val beta: Double = 0.007,230 private val dCutoff: Double = 1.0231) {232 private var xPrev: Double? = null233 private var dxPrev: Double = 0.0234 private var lastTime: Long = 0235236 fun filter(value: Double): Double {237 val now = System.nanoTime()238 val dt = if (lastTime == 0L) 1.0 / frequency239 else (now - lastTime) / 1_000_000_000.0240 lastTime = now241242 val prev = xPrev ?: return value.also { xPrev = it }243244 // Derivative245 val dx = (value - prev) / dt246 val edx = exponentialSmoothing(dx, dxPrev, alpha(dt, dCutoff))247 dxPrev = edx248249 // Adaptive cutoff250 val cutoff = minCutoff + beta * abs(edx)251 val result = exponentialSmoothing(value, prev, alpha(dt, cutoff))252 xPrev = result253 return result254 }255256 private fun alpha(dt: Double, cutoff: Double): Double {257 val tau = 1.0 / (2 * PI * cutoff)258 return 1.0 / (1.0 + tau / dt)259 }260261 private fun exponentialSmoothing(262 current: Double, previous: Double, alpha: Double263 ): Double = alpha * current + (1 - alpha) * previous264265 fun reset() {266 xPrev = null267 dxPrev = 0.0268 lastTime = 0269 }270}271```272273**Tuning:**274- `minCutoff` (1.0) — lower = smoother but more lag275- `beta` (0.007) — higher = less lag during fast movement but more jitter276- `frequency` (15.0) — match your camera frame rate277278## 2D Projection vs 3D Angles279280ML Kit gives 2D coordinates (screen projection) plus Z values. Why thresholds differ:281282| Factor | Effect |283|--------|--------|284| Camera distance | Farther = smaller angles appear in 2D |285| Camera angle | Side view vs front view changes projected angles |286| Body orientation | Rotated body changes landmark positions |287| Z-axis depth | ML Kit Z is relative, not absolute |288289**Production approach:** tune thresholds on 2D angles with the specific camera position your app uses. Don't try to reconstruct true 3D angles from ML Kit data — Z accuracy is insufficient.290291**Threshold tuning process:**2921. Record 10+ reps at expected camera distance2932. Log raw angles for each frame2943. Find the crossover points (where phase transitions)2954. Set thresholds with 10-15% margin from crossover2965. Apply 1€ filter, re-verify thresholds297298## Anti-Patterns299300- **Not closing ImageProxy** → blocks entire camera pipeline, no more frames301- **SINGLE_IMAGE_MODE for real-time** → processes one image, ignores stream. Use STREAM_MODE302- **Raw angle without filtering** → jitter causes false rep counts. Always filter303- **Hardcoded angle thresholds without testing** → 90° pushup threshold might be 80° or 100° depending on camera angle304- **Detecting both left and right side** → pick one side (left default). Both sides doubles noise305- **ML Kit on main thread** → `addOnSuccessListener` runs on main by default. Heavy processing should be moved off-main306