Last updated: November 2026
Camera-based sleep and drowsiness detection has quietly matured from a research demo into a shipping product category: driver-monitoring systems are now standard in new cars in the EU under the General Safety Regulation's second-phase mandates, wellness apps use nightly phone cameras as contactless monitors, and workplace-safety vendors sell fatigue alerts for industrial operators. The technical core, however, has stayed remarkably stable — face landmarks plus eye-closure statistics plus a temporal state machine, running on-device. What changed in 2026 is the tooling quality and the regulatory attention, both of which this update covers.
This guide walks the full product build: use-case framing, capture, feature extraction, temporal logic, mobile pipeline, on-device inference, failure states, privacy architecture, battery limits, evaluation methodology, and a testable project brief. Code examples reference the current MediaPipe Tasks API (the 2026-stable surface) and equivalent iOS/Android platform APIs.
Quick answer: a sleep-detection camera app should extract eye-closure and head-pose features with an on-device landmark model (MediaPipe FaceLandmarker or Apple Vision), feed PERCLOS-style statistics into a hysteresis state machine rather than a per-frame classifier, default to zero cloud uploads, and ship with explicit failure states for low light, occlusion, and glasses.
Choose the use case before choosing a model
"Sleep detection" is three different products, and every downstream decision depends on which one you are building:
- Overnight sleep tracking (wellness): camera watches a stationary subject for 6–9 hours. Latency budget is seconds; accuracy budget is generous; the hard constraints are battery, thermal, and privacy at night.
- Driver drowsiness alert (safety): latency budget is under 500 ms from eye closure to alert; false-alarm fatigue destroys the product; regulation (EU GSR driver monitoring) sets performance expectations for automotive contexts.
- Operator/shift fatigue monitoring (industrial): subjects at fixed workstations; accuracy matters, but consent architecture and union/employee agreements matter more — a technically perfect deployment can still be a product failure.
Pick wrong and you inherit the wrong constraints: teams building wellness trackers routinely burn months on latency optimizations they do not need, while safety-focused teams ship frame classifiers with no temporal hysteresis and drown users in false alarms.
For all three, the measurement primitive is the same: the fraction of time the eyes are closed over a rolling window (PERCLOS), plus head-pose and blink-dynamics context. A model choice that cannot give you reliable eye-state output at your target frame rate is the wrong model, whatever its leaderboard rank.
Capture frames reliably on Android and iOS
Capture is where most field failures originate, not in the model.
Android (CameraX, current in 2026): bind an ImageAnalysis use case with STRATEGY_KEEP_ONLY_LATEST — backpressure drops stale frames instead of queueing them, which is exactly what a real-time detector wants. Request 640×480 or 960×720 analysis resolution; landmark models do not benefit from 4K, but your thermal envelope suffers. Set Camera2Interop to lock exposure compensation up (+1 to +2 EV) if the use case is overnight monitoring in a dark bedroom, and expose a manual exposure control in settings — auto-exposure hunting in dim light produces landmark jitter that looks like drowsiness.
iOS (AVCaptureSession): use AVCaptureVideoDataOutput with a serial DispatchQueue, alwaysDiscardsLateVideoFrames = true, and sessionPreset = .vga640x480 or .hd1280x720. The iPhone's front camera supports 240 fps capture but you want 15–30 fps for sleep detection; request lower, and Core ML's thermal headroom thanks you.
Both platforms: acquire the camera while foregrounded. Background camera access is restricted by design on both OSes (see the FAQ) — overnight apps use a foreground service (Android, with a visible notification) or keep the screen dimmed with isScreenInput handling (iOS, with the proximity trick only where App Review permits). Plan your UX around that constraint from day one, because "runs in background invisibly" is an app-store rejection, not a feature.
Extract face, eye, mouth, and head features
The 2026 default choice for cross-platform apps is MediaPipe FaceLandmarker (Tasks API): it outputs 478 3D landmarks plus 52 ARKit-style facial blendshapes per frame, runs with GPU delegation on mid-range phones at 30+ fps, and loads from a single face_landmarker.task asset. The blendshape stream is the underrated part — eyeBlinkLeft / eyeBlinkRight give you a directly trainable eye-closure signal, while eyeLookUpLeft and friends help you distinguish "eyes closed" from "looking down."
Feature set worth logging per frame (all derivable from landmarks/blendshapes):
- EAR (Eye Aspect Ratio): eye-openness geometric ratio; robust to identity, weak to glasses glare.
- Blendshape blink values: normalized 0–1 closure; excellent when the subject wears glasses without heavy glare.
- Head pose (pitch/yaw/roll): from landmark geometry; distinguishes "asleep with head dropped" from "reading."
- Mouth openness (yawn proxy): MAR ratio; yawns are a fatigue context signal, not a sleep signal.
- Face presence/confidence: absence of a face for N seconds is itself a signal (subject left, camera blocked, or lens covered).
On iOS-only products, Apple's Vision framework (VNDetectFaceLandmarksRequest, and VNDetectFaceCaptureQualityRequest) gives you equivalent landmarks with zero cross-platform asset weight and excellent NEON/Core ML optimization. A common 2026 architecture: Vision on iOS, MediaPipe on Android, shared temporal logic in Kotlin Multiplatform or a thin Dart/C++ core.
Use a temporal state machine, not a frame label
The single most common architectural failure in this product category is treating each frame independently: "eyes closed in this frame → drowsy." Real subjects blink, squint, and glance down. The fix is a two-layer design:
Layer 1 — per-frame features: landmark/blendshape statistics (EAR, pose, presence) at 15–30 fps.
Layer 2 — temporal state machine with hysteresis:
AWAKE → DROWSY: PERCLOS ≥ 0.40 sustained 8 s (configurable)
DROWSY → ASLEEP: PERCLOS ≥ 0.60 sustained 20 s
ASLEEP → AWAKE: PERCLOS ≤ 0.20 sustained 10 s (asymmetric, to avoid flicker)
any → NO_FACE: face absent > 15 s (explicit failure state)
PERCLOS (PERcentage of CLOSure of the Eyes) is the validated drowsiness metric from driving research — 70–80% closure of the pupil over a rolling window, classically 1 minute. The 0.4/0.8 thresholds in that literature map to roughly the states above for consumer use; tune on your own labeled data, not on blog numbers.
Why hysteresis (different enter/exit thresholds): symmetric thresholds flicker at the boundary. A driver who oscillates between "drowsy" and "awake" every 2 seconds produces alert spam, and users disable alert-spammy apps within a week. Asymmetric thresholds with sustained-duration requirements are the difference between a demo and a product.
State machines also make evaluation honest: you score event-level precision/recall ("caught 19 of 22 micro-sleep events, raised 3 false alarms per hour"), which is what a safety reviewer or app-store description can stand behind — not "95% frame accuracy," which a coin-flip-with-blink-bias can also achieve.
Build the mobile pipeline step by step
A concrete reference pipeline, current as of November 2026:
- Permissions manifest (Android):
CAMERA,FOREGROUND_SERVICE,FOREGROUND_SERVICE_CAMERA,POST_NOTIFICATIONS; iOS:NSCameraUsageDescriptionwith a specific, honest string ("the camera checks whether your eyes are closed; video never leaves the device"). - Camera service: CameraX/AVCapture as above; 15 fps analysis cap for wellness, 30 fps for driver alerts.
- Landmark inference: MediaPipe
FaceLandmarkerin LIVE_STREAM mode with GPU delegate (or Vision on iOS). Convert output to your feature record. - Feature ring buffer: keep 60 seconds of per-frame features in memory (at 15 fps × ~10 floats, that is ~36 KB — trivial).
- State machine: pure function over the ring buffer; unit-testable without a camera (feed recorded feature streams).
- Event bus: state transitions emit events (DROWSY_ALERT, SLEEP_ONSET, NO_FACE) to UI, logging, and optional audio/haptic alert layers.
- Local store: nightly session summaries (not frames) in an on-device database; export as JSON/CSV.
- Optional upload: if the product has a cloud tier, upload only derived metrics, ideally end-to-end encrypted, with the camera-off switch killing the whole pipeline, not just the network.
Total on-device compute budget: on a 2023-class mid-range Android (Snapdragon 6-series), FaceLandmarker with GPU delegate runs ~8–12 ms/frame; at 15 fps that is under 20% sustained GPU load. This is a solved performance problem — do not reach for quantization or NPU delegates until you have measured otherwise.
Compare implementation choices
| Approach | Accuracy | Battery | Privacy | Effort | Best for |
|---|---|---|---|---|---|
| MediaPipe FaceLandmarker (on-device) | High (478 landmarks + 52 blendshapes) | Low–medium | Excellent (no frame leaves device) | Medium | Cross-platform apps, default choice |
| Apple Vision landmarks | High | Lowest | Excellent | Low | iOS-only products |
| Custom CNN classifier (eye-state, on-device) | Medium–high | Low | Excellent | High | Teams with labeled domain data |
| Cloud vision API | Highest | Device battery low | Poor (frames uploaded) | Low | Nothing user-facing; prototypes only |
| Radar/IR sensors | Medium (no video) | Lowest | Excellent | High (hardware) | Hardware products; in-car DMS |
The industry converged on the first two rows for software products. Cloud frame upload for sleep monitoring fails App Review scrutiny in most wellness categories since 2025, and it deserves to.
Make on-device inference the default
Three reasons, in descending order of strength:
- Privacy is the product. A camera that watches someone sleep is the most intimate sensor in consumer electronics. "Your video never leaves this phone" is not a nice-to-have claim — it is the only positioning that survives both user questioning and regulator attention (GDPR Article 9 treats biometric-derived health data as special-category; on-device processing with no transmission is the cheapest way to never enter that regulatory surface).
- Latency and reliability. Driver drowsiness alerts over a network stack are hostage to tunnels and dead zones. Local inference fires in milliseconds, offline.
- Unit economics. Cloud vision inference costs $0.50–$2.00 per overnight session per user at typical API pricing. On-device costs zero marginal. Wellness apps have subscription price points that cannot carry that.
On-device is also now the easy path: MediaPipe Tasks ships prebuilt mobile packages (Android AAR, iOS SPM/CocoaPods, plus web WASM) with the model assets versioned alongside. The remaining engineering work is capture quality and temporal logic — exactly where it should be.
Low light, occlusion, and bias need explicit failure states
Every production deployment hits these; design for them as first-class states, not exceptions:
- Low light / darkness: overnight rooms are dark. IR illumination needs hardware; software-only apps must detect "image too dark for landmarks" (landmark confidence collapse) and degrade gracefully — switch to audio/motion sensing if available, or surface "monitoring paused, too dark" instead of silently reporting "awake."
- Occlusion (blanket, hand, glasses, mask): distinguish "no face detected" from "face partially visible." A CPAP mask, heavy blanket coverage, or glare on glasses each produce distinctive partial-landmark signatures. Log them as distinct events; users will ask why monitoring stopped, and "camera saw no face for 6 hours" without a reason is a churn generator.
- Demographic bias: landmark models have measurably worse eye-state accuracy for some eye shapes, skin tones in low light, and users with ptosis or asymmetric faces (Bell's palsy). Mitigations: per-user calibration (a 20-second "eyes open / eyes closed" enrollment), confidence-weighted thresholds, and honest accuracy claims in marketing. If your alert thresholds were tuned on one demographic, your product will false-alarm its way out of the market.
- Multiple faces: a partner in frame. Decide explicitly (track primary face via largest-box heuristic + enrollment template) and expose a setting; otherwise your app reports shared-bed users as insomniacs.
Privacy needs more than camera permission
A consent-compliant 2026 architecture, minimum viable set:
- Just-in-time disclosure: explain, before first camera use, what is processed and what is never stored. Screenshots of the actual on-screen states help; boilerplate does not.
- No frame persistence by default. Derived features and session summaries only. If debugging requires frame capture, gate it behind an opt-in that auto-expires in 24 hours and watermarks exports.
- Camera-off hardware equivalence: one tap kills capture (not just hides UI). A visible indicator while monitoring (Android foreground-service notification, iOS recording-style indicator is automatic but your own in-app banner helps) keeps trust.
- Special-category data awareness: if you store or transmit sleep classifications, you are processing health-adjacent biometric data — GDPR special category, HIPAA-adjacent if a US clinic deploys it, and both Apple and Google app-review health sections want substantiated claims. Either stay fully local, or budget real legal review.
- Deletion that works: "delete my data" must remove derived metrics too, including any encrypted cloud backups of summaries. Test the deletion path; regulators and one-star reviews both target it.
- Employee-monitoring deployments need consent architecture (opt-in, aggregate-only reporting to employers, works-council review in the EU). A fatigue product sold as workplace surveillance acquires a different and much heavier legal envelope.
Battery and thermal limits shape the product
Overnight monitoring is the harshest sustained workload most phones see short of navigation:
- At 15 fps continuous capture + inference, expect 8–14%/hour battery drain on mid-range devices, less on flagships with efficient NPUs. A 9-hour session is not survivable unplugged for many devices — so design for "phone on charger, screen dimmed" as the primary overnight mode and say so plainly in onboarding.
- Thermal throttling on sustained camera work reduces inference performance after 20–40 minutes on some devices; adaptive frame-rate (drop to 5 fps in stable ASLEEP state, return to 15 fps on any transition candidate) cuts both heat and battery roughly in half with minimal event-detection cost. This is the highest-leverage optimization in the whole stack.
- Avoid wakelock-only designs; modern Android doze and iOS background limits will kill them. Foreground service + partial wakelock on Android, and dimmed-screen foreground on iOS, are the sustainable patterns.
- Publish real numbers. "Uses about 10% per night while charging" is trust-building; silence breeds the assumption of worse.
Evaluate events, not flattering frame accuracy
Frame-level accuracy is the vanity metric of this field. Design evaluation around events and user outcomes:
- Event-level precision/recall: on labeled recordings (micro-sleeps, sleep onsets, camera-blocked stretches), report how many events were caught and how many alerts were false. Target for a driver product: recall ≥ 0.85 on events ≥ 3 s, false alerts ≤ 2/hour; wellness products can trade recall for even fewer false alerts.
- Latency distribution: closure-onset → alert, p50 and p95. A safety product lives and dies on p95.
- Stratified cohorts: accuracy by lighting, glasses, skin tone, camera angle. Publish the worst cohort, not the average — the average hides the users you will fail first.
- Longitudinal drift: camera position shifts over nights; pillows occlude; users change habits. Re-evaluate after 30 nights, not 30 minutes.
- Data for all this: collect opt-in labeled recordings from a diverse pilot group (pay participants; consent forms for biometric recording are non-negotiable), or license from drowsiness-driving research corpora where terms allow.
Fail-safe UX for wellness and safety contexts
The alert layer deserves product-level care:
- Escalating alerts for driver contexts: stage 1 soft audio cue, stage 2 insistent tone + vibration, stage 3 "pull over" prompt with supervisor/telematics escalation where deployed. Alerts must be impossible to permanently dismiss with one accidental tap while drowsy.
- Quiet failure for wellness: a sleep tracker that pings at 3 a.m. because it lost the face is worse than useless. Fail silently to logging, summarize in the morning ("monitoring paused 02:10–03:40, room too dark").
- Never diagnose. "You appeared asleep" is fine; "you have sleep apnea" is a regulated medical claim. Word the entire app against diagnosis unless you are pursuing it as a medical device (a much longer road — separate class, separate article).
- Honest absence reporting: "no data, camera blocked" shown plainly beats silent gaps that erode every downstream insight.
Turn the plan into a testable project brief
Compress this guide into a one-page brief your team can execute against:
- Product statement: [Wellness overnight tracker | Driver alert | Operator monitor] for [platforms], on-device only, no frame upload.
- Core metric: event-level recall ≥ [x] at false-alert rate ≤ [y]/hour, stratified across lighting/glasses/demographic cohorts.
- Pipeline: CameraX/AVCapture 15–30 fps → MediaPipe FaceLandmarker (or Vision) → ring buffer (60 s) → hysteresis state machine (thresholds + sustained durations as config) → event bus → UI/alerts/summary store.
- Failure states enumerated: NO_FACE, TOO_DARK, OCCLUDED, MULTI_FACE, THERMAL — each with defined UX.
- Privacy commitments: no frame persistence, one-tap kill, deletion path tested, special-category data handling documented.
- Milestones: M1 recorded-data replay harness (state machine + eval on labeled streams); M2 live capture on one device; M3 multi-device pilot (n ≥ 20, diverse); M4 battery/thermal hardening; M5 privacy review + store submission.
Building M1 before any camera work is the highest-ROI sequencing decision in this brief: the replay harness makes the temporal logic testable in CI and turns every later field failure into a reproducible unit test.
Frequently Asked Questions
How can a camera detect whether someone is asleep?
By extracting per-frame face signals — eye-closure ratios (EAR/blink blendshapes), head pose, and face presence — then applying temporal logic: eyes ≥ 60–80% closed, head dropped, sustained for tens of seconds, transitions into an ASLEEP state. No single frame decides; the pattern over time does.
What is Eye Aspect Ratio in drowsiness detection?
EAR is the ratio of eye-landmark vertical distances to horizontal distance. Open eyes ≈ 0.25–0.35; closed ≈ 0.1–0.15. Per-subject calibration matters because baseline varies; the ratio is scale- and distance-invariant, which is why it survives camera shake.
Is PERCLOS better than a single eye-closure threshold?
Yes — PERCLOS (percentage of eye closure over a rolling window) is the validated drowsiness metric in driving research, and it is inherently robust to single blinks. A single-frame threshold classifies every blink as a micro-sleep; PERCLOS distinguishes them by construction.
Can MediaPipe detect closed eyes in real time?
Yes. The FaceLandmarker task outputs 478 landmarks and 52 blendshapes — including eyeBlinkLeft/Right — at 30+ fps on mid-range phones with GPU delegation, in LIVE_STREAM mode. It is the standard 2026 cross-platform choice; Apple Vision provides the equivalent on iOS.
Can a mobile camera run continuously in the background?
Not invisibly. Android requires a foreground service with a visible camera-type notification; iOS restricts background camera access to specific sanctioned uses. Overnight apps keep the session alive foregrounded with a dimmed screen, or a visible foreground service. Anything else gets killed by the OS or rejected in review — by design, for user privacy.
Should drowsiness inference run on-device or in the cloud?
On-device, for consumer products: privacy (special-category biometric data never leaves the phone), latency (alerts in milliseconds, offline), and cost (zero marginal inference spend). Cloud inference only survives in research settings or when fusing many sensors server-side in consented enterprise deployments.
Can this app be used for driving safety or medical diagnosis?
Driver drowsiness alerting is an established product category (and EU-regulated in new cars via GSR driver-monitoring requirements) — but selling into automotive means automotive-grade validation. Medical diagnosis (apnea, hypersomnia) is a regulated medical-device path in every major jurisdiction; consumer apps must word claims as wellness tracking, never diagnosis, unless they complete that process.
Key Takeaways Before You Build
The stack that works in 2026 is unglamorous and reliable: platform camera APIs at modest resolution, an on-device landmark model (MediaPipe FaceLandmarker or Apple Vision), features over frames, a hysteresis state machine with explicit failure states, and privacy architecture that keeps every pixel local. The teams that succeed spend their innovation budget on temporal logic, evaluation harnesses, and honest UX — not on bigger models. Build the replay harness first, calibrate per user, report event-level accuracy by cohort, and let "video never leaves the device" be the headline feature it deserves to be.
Sources
- https://developers.google.com/mediapipe — MediaPipe Tasks API and FaceLandmarker documentation (checked November 2026)
- https://developer.apple.com/documentation/vision — Apple Vision framework face-landmark requests
- https://developer.android.com/training/camera/camerax — CameraX ImageAnalysis and foreground-service guidance
- https://developer.apple.com/documentation/avfoundation — AVCaptureSession configuration reference
- https://eur-lex.europa.eu/eli/reg_del/2021/1341/oj — EU General Safety Regulation implementing acts (driver drowsiness monitoring requirements)
- https://gdpr-info.eu/art-9-gdpr/ — GDPR Article 9, special categories of personal data
- https://arwriterai.com/en/blog/ — ARWriter English blog (publisher's related reading)