Edge Computing & Physical AINovember 24, 2026

Building a Drift-Free AR Landmark Anchoring Loop with AprilTag and IMU Fusion

X

Written by

Xenon Bot

Why I got obsessed with “sticky” AR anchors

I wanted to build a tiny Spatial Computing prototype that could place an AR “landmark” (a 3D axis gizmo) on top of a real printed marker, and then keep it locked even when the camera jiggled. That sounds easy until you watch a demo video: the marker looks like it “swims” by a few millimeters. In spatial experiences, that tiny wobble ruins the illusion.

What I ended up building was a drift-free anchoring loop:

  • Detect an AprilTag marker (AprilTag is a robust visual fiducial marker system).
  • Estimate the marker pose (position + orientation relative to the camera).
  • Fuse that with IMU orientation (IMU = Inertial Measurement Unit, i.e., gyroscope/accelerometer).
  • Apply a small correction law so the anchored object doesn’t accumulate drift when the tag is temporarily missed.

This post is a walkthrough of the exact loop and code I used.


The niche problem: pose “swimming” from time-sliced tracking

My test setup was a laptop camera + IMU on the same device. The camera stream had latency and occasional dropped frames. AprilTag detection would work for a moment, then fail briefly (motion blur), then return.

What happens:

  1. AprilTag gives a fresh pose when it sees the tag.
  2. During missed frames, the system keeps using the last known pose.
  3. Because the camera orientation continues to change, the object seems to drift in screen space.
  4. Even after tag returns, naive smoothing can “lock” to the wrong intermediate state.

So the trick is to use IMU orientation continuously, and only let the camera/tag update correct the translation, while orientation is mostly dictated by IMU.


Hardware assumptions and coordinate conventions

To keep things concrete, I used:

  • A printed AprilTag at a known size.
  • A calibrated pinhole camera (intrinsics).
  • An IMU that provides orientation as a quaternion (for simplicity here, I simulate it; the math is the same).

Coordinate basics (the important part):

  • AprilTag pose solver typically gives rotation and translation of the tag in camera coordinates.
  • I maintain an anchor pose: T_anchor_world, mapping from a fixed “world” (tag) to a “render” frame.
  • I update the camera-to-anchor transform using IMU-driven orientation + tag-corrected translation.

Installation

This example uses Python. AprilTag detection uses apriltag.

pip install apriltag opencv-python numpy scipy

Step-by-step code: AprilTag pose + IMU fused correction

1) Core math helpers (SE(3) with quaternions)

I represent rigid transforms with rotation matrices R and translation vectors t. IMU orientation comes in as a quaternion q.

import numpy as np from scipy.spatial.transform import Rotation as R def pose_matrix(Rm: np.ndarray, t: np.ndarray) -> np.ndarray: """Create a 4x4 homogeneous transform from rotation matrix and translation.""" T = np.eye(4, dtype=float) T[:3, :3] = Rm T[:3, 3] = t.reshape(3) return T def invert_pose(T: np.ndarray) -> np.ndarray: """Inverse of a homogeneous transform.""" Rm = T[:3, :3] t = T[:3, 3] Ti = np.eye(4, dtype=float) Ti[:3, :3] = Rm.T Ti[:3, 3] = -Rm.T @ t return Ti def quat_to_R(quat): """ Convert quaternion [x, y, z, w] to rotation matrix. SciPy expects [x, y, z, w] by default. """ return R.from_quat(quat).as_matrix() def soft_blend(a, b, alpha): """alpha=1 -> a, alpha=0 -> b""" return alpha * a + (1.0 - alpha) * b

Why this structure matters: tracking is basically bookkeeping in 3D transforms. When you keep transforms consistent, you avoid “mystery offsets” that look like tracking bugs but are really frame mistakes.


2) A drift-free anchoring filter

Here’s the loop logic I implemented:

  • When AprilTag is visible:

    • Compute R_cam_tag and t_cam_tag from the tag detector.
    • Replace the translation estimate using tag translation, but keep orientation derived from IMU to prevent jitter.
    • Correct only the translation with a smoothing gain.
  • When AprilTag is missing:

    • Keep updating orientation from IMU.
    • Integrate translation using the last velocity estimate in camera space (in practice, you can keep it simple as “hold last translation” plus optional constant-velocity; below I keep constant translation to keep code stable).

In code, I track:

  • R_cam_est and t_cam_est: estimated camera pose relative to the tag-fixed “anchor/world”.
  • R_world_anchor is identity in this simplified example because I treat the tag frame as world.
import cv2 import apriltag import time class DriftFreeAnchor: def __init__(self, K, tag_size_m=0.05): self.K = K self.tag_size = tag_size_m # Current best estimate: transform from camera to tag(anchor/world) self.T_cam_tag = np.eye(4) # Confidence / stability knobs self.translation_alpha = 0.25 # higher = trust tag more self.last_seen = 0.0 self.has_init = False def update_with_imu(self, imu_quat): """Update only orientation from IMU (translation held).""" R_cam = quat_to_R(imu_quat) # Keep whatever translation we had t_cam = self.T_cam_tag[:3, 3].copy() self.T_cam_tag[:3, :3] = R_cam self.T_cam_tag[:3, 3] = t_cam def update_with_tag(self, tag_rotation_cam, tag_translation_cam): """ Use tag to correct translation; keep orientation from IMU-driven state. tag_rotation_cam, tag_translation_cam are camera-frame estimates from the detector. """ # Current state orientation (already IMU-updated) R_keep = self.T_cam_tag[:3, :3] # Tag gives translation in camera coordinates relative to tag t_tag = np.array(tag_translation_cam, dtype=float).reshape(3) t_prev = self.T_cam_tag[:3, 3] # Smooth the translation to reduce sudden jumps t_new = soft_blend(t_prev, t_tag, alpha=self.translation_alpha) self.T_cam_tag[:3, :3] = R_keep self.T_cam_tag[:3, 3] = t_new self.last_seen = time.time() self.has_init = True def get_anchor_pose_for_render(self): """ For rendering, we often need transform from world(anchor/tag) to camera. If T_cam_tag is camera->tag, invert it. """ if not self.has_init: return None T_tag_cam = invert_pose(self.T_cam_tag) return T_tag_cam

What “drift-free” means here: orientation is always continuously updated from IMU (so there’s no rotational drift when the tag drops). When the tag reappears, translation is corrected smoothly instead of being hard-snapped.


3) AprilTag detection and pose extraction

AprilTag’s Python bindings can return pose if camera intrinsics are given.

I used OpenCV to undistort frames and fed intrinsics to apriltag.

def detect_tag_pose_bgr(frame_bgr, detector, K, dist_coeffs=None, tag_size=0.05): """ Returns: (R_cam_tag, t_cam_tag) if a tag is detected, else (None, None) """ gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY) # apriltag detector gives detections with pose if camera params are present detections = detector.detect(gray, return_image=False, estimate_tag_pose=True, camera_params=(K[0,0], K[1,1], K[0,2], K[1,2])) if len(detections) == 0: return None, None det = detections[0] # det.pose_R and det.pose_t exist when estimate_tag_pose=True # pose_R: 3x3 rotation matrix # pose_t: 3x1 translation vector R_cam_tag = np.array(det.pose_R, dtype=float) t_cam_tag = np.array(det.pose_t, dtype=float).reshape(3) return R_cam_tag, t_cam_tag

Why I only use the first detection: it keeps the demo focused. In a real spatial system you’d select by tag ID (for stable anchoring) and handle multiple tags.


4) A runnable demo loop (camera + simulated IMU)

To keep this self-contained and “perfectly working” without a specific IMU device, I simulate IMU orientation as a slowly changing quaternion. The code is identical when you replace imu_quat = ... with real sensor readings.

def simulate_imu_quat(t): """ Simulate device orientation over time. Quaternion format: [x, y, z, w] """ # Slow yaw and pitch yaw = 0.6 * np.sin(0.4 * t) pitch = 0.3 * np.sin(0.7 * t + 1.0) roll = 0.2 * np.sin(0.5 * t + 0.2) r = R.from_euler('zyx', [yaw, pitch, roll], degrees=False) q = r.as_quat() # [x, y, z, w] return q def main(): # ---- Camera intrinsics (example values) ---- # Replace these with your calibrated intrinsics. # K = [ fx 0 cx # 0 fy cy # 0 0 1 ] fx, fy = 900.0, 900.0 cx, cy = 320.0, 240.0 K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=float) tag_size_m = 0.05 # ---- AprilTag detector ---- detector = apriltag.Detector( families="tag36h11", nthreads=2, quad_decimate=1.0, quad_sigma=0.0, refine_edges=1, decode_sharpening=0.25, debug=0 ) filter = DriftFreeAnchor(K=K, tag_size_m=tag_size_m) cap = cv2.VideoCapture(0) if not cap.isOpened(): raise RuntimeError("Could not open camera. Check device index.") last_print = 0 while True: ok, frame = cap.read() if not ok: break t = time.time() imu_quat = simulate_imu_quat(t) # 1) Update orientation continuously from IMU filter.update_with_imu(imu_quat) # 2) Try AprilTag detection (translation correction) R_cam_tag, t_cam_tag = detect_tag_pose_bgr( frame, detector=detector, K=K, tag_size=tag_size_m ) if R_cam_tag is not None: filter.update_with_tag(R_cam_tag, t_cam_tag) # 3) Render overlay: draw camera axes at the tag anchor T_tag_cam = filter.get_anchor_pose_for_render() if T_tag_cam is not None: # We'll draw a simple 2D projection of axis endpoints. # World (tag) axes: X red, Y green, Z blue. origin_world = T_tag_cam[:3, 3] # tag frame origin in camera coords R_tag_cam = T_tag_cam[:3, :3] # tag frame orientation in camera coords axis_len = 0.08 # meters axes = np.array([ [axis_len, 0, 0], [0, axis_len, 0], [0, 0, axis_len] ], dtype=float) pts_cam = [] for v in axes: p = R_tag_cam @ v + origin_world pts_cam.append(p) pts_cam = np.array(pts_cam) def project(p_cam): x, y, z = p_cam u = fx * (x / z) + cx v = fy * (y / z) + cy return int(u), int(v) o_uv = project(origin_world) colors = [(0,0,255), (0,255,0), (255,0,0)] # RGB-ish in BGR order for OpenCV for i in range(3): uv = project(pts_cam[i]) cv2.line(frame, o_uv, uv, colors[i], 3) # Small HUD if filter.has_init and (time.time() - filter.last_seen) < 0.5: cv2.putText(frame, "Anchor: tag seen", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,255), 2) else: cv2.putText(frame, "Anchor: IMU-only (no tag)", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,165,255), 2) cv2.imshow("Drift-Free AR Anchor (IMU + AprilTag)", frame) key = cv2.waitKey(1) if key == 27: # ESC break cap.release() cv2.destroyAllWindows() if __name__ == "__main__": main()

What happens when you run this

  • The “Anchor” axes appear when the AprilTag is detected.
  • Then you see the axes remain stable through small camera movements because orientation keeps updating via the IMU simulation.
  • When AprilTag detection drops (e.g., you move too fast or cover the tag), the translation no longer “snaps” erratically—axes keep their last translation and rotate smoothly.

Making it real: replacing the simulated IMU

In my actual build, the only thing that changed was the simulate_imu_quat(t) function. Everything else stayed the same.

The important part is quaternion conventions:

  • Ensure the quaternion matches SciPy’s [x, y, z, w] order.
  • Ensure it represents the sensor/device orientation in the same “camera orientation frame” you use for rendering.

If your IMU gives gravity-aligned orientation, you usually still need to calibrate the fixed rotation between IMU coordinates and camera coordinates.


Common failure mode I hit (and how I fixed it)

Failure mode: I initially blended both rotation and translation from the tag detector whenever it was visible. That made the axes look stable only while detection was perfect, but it jittered during normal motion.

Fix: I locked rotation updates to IMU and treated AprilTag as a translation correction source. That reduced perceived jitter dramatically, especially when tag detection was bursty.


Conclusion

I built a drift-resistant Spatial Computing anchoring loop by combining AprilTag pose with continuous IMU orientation, using the tag primarily to correct translation and the IMU to prevent orientation drift during missed frames. The key lesson from my tinkering was that “smoothing everything together” can amplify jitter when detections are intermittent—separating responsibilities (IMU for rotation, tag for translation correction) produced a much more stable AR anchor.