Wearable vision middleware · Paper submitted Apr 2026

CORTEX

Battery-aware middleware that decides which wearable camera frames are worth sending to a VLM.

Solo Researcher & Engineer · Solo · 9 days (Mar 30 – Apr 7, 2026)

60%+
Target cut in frames sent to VLM APIs (design target)
2×
Target battery extension (design target)
176
pytest tests across capture, optimizer, memory, graph and compiler
CORTEX filtering redundant camera frames

Context

Smart glasses stream ~30 fps to VLM APIs even when nothing in the scene has changed.

The problem

Static scenes, unchanged whiteboards and blurry frames still cost tokens and drain the wearable battery on every call. The fix had to be a drop-in layer that decides in real time whether a frame is worth sending, then shrinks it, with no hardware changes or model retraining.

What I owned

I designed and built the SDK alone, and wrote the accompanying arXiv paper on the 4-layer architecture and benchmark method.

Core

Python 3.11+NumPyPillowhttpx

Vision

OpenCVscikit-image (SSIM)Laplacian blur detectionMSER text detectionSpectral saliency

Testing

pytest

Architecture

Four layers sit between the camera and the model: capture gating, compression, routing and context memory.

4-Layer Middleware: Gate → Crop → Route → Memory

swipe
Smart Glasses CameraL1 IMU GateL1 Blur DetectorL1 SSIM FilterL2 Scene ClassifierL2 ROI Crop + EncodeL3 VLM RouterL4 Context MemoryClaude / GPT /GeminiCircuit Breaker
  1. Critical path
  2. Smart Glasses Camera
  3. →L1 IMU Gate
  4. →L1 Blur Detector
  5. →L1 SSIM Filter
  6. →L2 ROI Crop + Encode
  7. →L3 VLM Router
  8. →Claude / GPT / Gemini

Highlighted: the path an accepted frame takes. Most frames stop at an L1 gate.

Key decisions

Each L1 and L2 choice trades a little sensitivity for a large cut in what reaches the API.

Decision 1

SSIM instead of pixel difference for scene change

Problem
Naive pixel subtraction flags minor lighting changes and JPEG artifacts as a new scene.
Options
  • Pixel diff
  • Structural Similarity (SSIM)
Decision
An SSIM gate against a persisted reference frame. The threshold follows the battery mode: 0.90 (Aggressive), 0.80 (Balanced, default), 0.65 (Power save).
Result
Robust to small lighting and compression noise, and integrators can tune sensitivity against battery savings.
Trade-off
A sudden flash drops SSIM to ~0.4 with no semantic change, so the threshold needs tuning per environment.

Decision 2

Run the cheap blur check before SSIM

Problem
SSIM is the most expensive L1 check, and blurry frames are useless anyway.
Options
  • SSIM on every frame
  • Laplacian variance first, SSIM only on sharp frames
Decision
Laplacian variance (O(n)) runs before SSIM (O(n log n)).
Result
The blur check drops ~15% of frames before the more expensive comparison runs.
Trade-off
A blur threshold set too high also rejects legitimately low-texture scenes, such as all-black or all-white frames.

Decision 3

Encode for the network, not one fixed setting

Problem
Accepted frames still need to be as small as possible without hurting VLM answers.
Options
  • One fixed resolution and quality
  • Resolution, format and quality picked per network condition
Decision
Pick the encoding from the network condition: WiFi 1024 px WebP q85, LTE 640 px WebP q70, weak signal 320 px JPEG q60, and queue frames while offline.
Result
Bytes per frame track the link instead of the camera; 60%+ payload reduction is the design target, not yet benchmarked.

Measurement

Numba JIT cut the saliency DFT kernel from 0.421 ms to 0.185 ms per 640×480 frame, and the whole L2 stage runs in about 9.5 ms.

Saliency DFT kernel per 640×480 frame (baseline → Numba JIT)

Before
0.421 ms
After
0.185 ms
Network
None: local, MacBook Pro M2, synthetic frames
Samples
100
p50
0.185 ms (median of 100, JIT)

Reliability

No single bad frame can crash the pipeline, and 176 pytest tests cover the built layers.

  • 176 pytest tests across optimizer (59), memory (35), graph (33), capture (29) and compiler (20). The SSIM gate, blur detector, ROI crop and adaptive encoder each have isolated tests using synthetic frames.
  • A webcam demo with a live HUD showed accepted and rejected counts, SSIM scores and payload sizes across 3 scene types: static whiteboard, hand movement and walking.
  • L1 gate errors such as an OpenCV decode failure return (False, 0.0), so the frame is dropped instead of crashing the pipeline.
  • Out-of-bounds L2 ROI crops are clamped with np.clip and never raise IndexError.
Edge cases covered (5)
  • All-black / all-white frames: Laplacian variance = 0 → rejected as blurry before SSIM
  • Scene flash (sudden brightness change): SSIM drops to ~0.4 even with no semantic change → threshold tuning guide in docs
  • MSER on low-contrast text: falls back to a center crop when fewer than 5 text regions are detected
  • Tiny frames (<64×64): spatial pyramid pooling skipped, direct encode
  • Network switch WiFi→LTE mid-session: adaptive encoder re-reads network state per frame (no restart needed)

Limits and scale

L1 and L2 are built and tested, while routing and the headline savings are still unproven.

TodayThe L3 VLM router's circuit breaker is planned, not built.

At scaleTrack the error rate per provider, open the circuit after more than 3 consecutive failures (30 s), and fall back to the next configured model.

TodayValidation used a webcam demo, not glasses hardware, so battery impact has not been measured on a device.

At scale—

TodaySSIM and blur thresholds are global, and a scene flash can trigger false positives.

At scale—

Engineering deep divePipelines, code flow and implementation notes

Measured L2 profile (paper §6.1, MacBook Pro M2, 640×480, median of 100 runs after 10 warm-ups)

text_roi_mser 8.11 ms (85% of L2) · motion_map 0.95 ms · saliency_dft 0.43 ms · center_crop 0.03 ms · score_fusion 0.01 ms · ema_smooth 0.003 ms. Total ≈ 9.5 ms per frame; dead-node elimination brings POWER_SAVE to ≈ 9.1 ms.
Saliency DFT kernel: baseline 0.421 ms → vectorized 0.225 ms (1.9×) → Numba JIT 0.185 ms (2.3×), max numerical difference < 1.2e-7.
Payload, battery and API-cost figures (60%+, 2×, 50%+) are design targets in the paper's Table 4, not measurements.

L1: Capture — "Should we process this frame?"

markdown
New camera frame arrives
  │
  ├─ IMU Gate (motion sensor check)
  │    └─ acceleration below threshold? → skip (camera still, likely static scene)
  │
  ├─ Blur Detector (Laplacian variance)
  │    └─ variance < blur_threshold? → skip (frame too blurry for VLM)
  │
  ├─ Scene Change Detector (SSIM vs last accepted frame)
  │    ├─ SSIM > similarity_threshold (e.g. 0.92)? → skip (scene unchanged)
  │    └─ SSIM ≤ threshold → ACCEPT
  │         └─ update "last accepted frame" reference
  │
  Result: maximizes camera-off time; only meaningful frames pass to
  Target: 60%+ of frames filtered before any encode/API call

L2: Compress — "What part matters? How small can it be?"

markdown
Accepted frame (from L1)
  │
  ├─ Scene Classifier
  │    ├─ "text-heavy" → MSER text region detection → crop to text bounding box
  │    ├─ "face/object" → spectral saliency map → crop to salient region
  │    └─ "general"    → center-weighted crop (safe fallback)
  │
  ├─ Hybrid ROI Crop
  │    └─ expand bounding box by context_margin (avoid cutting off context)
  │         └─ clamp to frame boundary
  │
  ├─ Adaptive Encoder
  │    ├─ WiFi               → WebP quality 85, max 1024px
  │    ├─ LTE                → WebP quality 70, max 640px
  │    ├─ weak signal        → JPEG quality 60, max 320px
  │    └─ offline            → queued until the link returns
  │
  └─ Output: compressed WebP / JPEG bytes

L1 Core — SSIM scene change gate

python
def should_process_frame(self, frame: np.ndarray) -> tuple[bool, float]:
    """
    Returns (should_process, ssim_score).
    Rejects frames too similar to the last accepted frame.
    """
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # First frame always accepted
    if self._last_frame is None:
        self._last_frame = gray
        return True, 0.0

    score, _ = ssim(self._last_frame, gray, full=True)

    if score >= self.similarity_threshold:   # e.g. 0.92
        return False, score                  # scene unchanged → skip

    self._last_frame = gray                  # update reference
    return True, score

More notes

State across frames: the SSIM reference frame and ROI classifier state persist across frames, which gives temporal coherence without a full video encoder.
Drop-in API: integrators call pipeline.process(frame) and receive (should_call_vlm, payload_bytes), with no changes to existing VLM integration code.
Paper: accompanied by an arXiv paper (cortex-arxiv-v5) formalizing the 4-layer architecture and benchmark methodology.

← All projects