Skip to content

When Sim-Trained Robot Policies Fail on Real Hardware: A 4-Axis Calibration Workflow for Optics, Friction, Mass, and Latency

Diagnose why sim-trained robot policies fail on real hardware using a 4-axis measure-calibrate-randomize workflow for optics, latency, friction, and mass.

Contents

Key takeaways

  1. Blindly widening domain randomization ranges degrades policy precision and slows convergence; always follow Measure, Quantify, Calibrate, and Randomize in strict order.
  2. On Axis 1 (optics), run OpenCV cv2.calibrateCamera() to obtain camera matrix K and distortion (k1, k2, p1, p2, k3), transfer them into MuJoCo <camera> (fovy or sensorsize/focalpixel/principalpixel), and lock hardware auto-exposure and auto-white-balance.
  3. On Axis 2 (control latency), measure end-to-end camera-capture, inference, and actuator-bus lag in control steps, then model it with a collections.deque FIFO buffer or Isaac Lab DelayedPDActuatorCfg.
  4. On Axes 3 and 4 (friction and mass), run an inclined-plane slip test (μs = tan θ) for geom_friction and weigh real links/payloads for body_mass before enabling randomize_rigid_body_material and randomize_rigid_body_mass.

A robot policy that succeeds reliably in simulation often misses targets, slips during grasps, or oscillates violently on physical hardware. The knee-jerk response is to widen every domain randomization range until training covers every conceivable condition. Yet widening ranges around an uncalibrated nominal model forces the policy into overly conservative behavior—reducing manipulation precision and sometimes preventing convergence altogether.

Building on the fundamentals covered in the Sim-to-Real gap and domain randomization overview, this guide lays out a measurement-first engineering workflow across four concrete axes—camera optics, control latency, surface friction, and link mass—using OpenCV 4.x, MuJoCo 3.16.0, Ultralytics YOLO, and NVIDIA Isaac Lab.

Why Measure-Quantify-Calibrate-Randomize Beats Blind Range Widening

Reality gaps consist of two separate error components: nominal bias (the simulator’s center point differs from hardware) and environmental variance (lighting, surface wear, or bus jitter fluctuate between trials). Domain randomization handles variance, not gross bias. Every physical axis should pass through four ordered steps:

  1. Measure: Collect direct physical readings using a calibration checkerboard, timestamped loop logs, an inclined plane, and a digital scale.
  2. Quantify: Record the numerical gap between measured hardware values and current MJCF/USD defaults in pixels, milliseconds, friction coefficients, or grams.
  3. Calibrate: Replace the simulator’s nominal parameters with the measured baseline values to eliminate systematic bias first.
  4. Randomize: Add randomization bounds strictly around the calibrated baseline to reflect measurement uncertainty and real operating drift.

Following this sequence isolates which axis causes real-world failure instead of masking one bug by over-randomizing three unrelated parameters.

Axis 1: Camera Optics, Intrinsics Alignment, and Vision Encoder Transfer

Before tuning any visual randomization, verify that the physical camera’s coordinate convention matches the simulator—see the URDF camera optical frame guide for camera_link versus camera_link_optical alignment. Next, calibrate the real lens intrinsics.

Following the OpenCV 4.x Camera Calibration Tutorial, running cv2.calibrateCamera() on checkerboard captures returns the 3×33 \times 3 intrinsic matrix KK (focal lengths fx,fyf_x, f_y and principal point cx,cyc_x, c_y) along with the five-element distortion vector (k1, k2, p1, p2, k3) covering radial distortion (k1,k2,k3k_1, k_2, k_3) and tangential distortion (p1,p2p_1, p_2). Convert calibrated vertical focal length fyf_y and image height HH into MuJoCo’s vertical field of view fovy (degrees) via:

fovy=2arctan⁡ ⁣(H2fy)⋅180π\text{fovy} = 2 \arctan\!\left(\frac{H}{2 f_y}\right) \cdot \frac{180}{\pi}

In the MuJoCo MJCF XML Reference, <camera> supports either fovy for symmetric pinhole models or the explicit intrinsic attributes resolution, sensorsize, focalpixel, and principalpixel. When sensorsize is defined, MuJoCo activates the full intrinsic model and ignores fovy; if both focal and focalpixel appear, pixel units take precedence.

import math
import numpy as np
import cv2

# Example cv2.calibrateCamera() output for a 640x480 camera
K = np.array([[612.4, 0.0, 324.8],
              [0.0, 611.9, 236.2],
              [0.0,   0.0,   1.0]], dtype=np.float64)
dist = np.array([-0.14, 0.08, 0.001, -0.0005, 0.0], dtype=np.float64)
w, h = 640, 480

fovy_deg = 2.0 * math.degrees(math.atan2(h, 2.0 * K[1, 1]))
px_offset = K[0, 2] - (w / 2.0)
py_offset = K[1, 2] - (h / 2.0)
print(f'<camera name="cam_front" resolution="{w} {h}" fovy="{fovy_deg:.3f}"/>')
print(f'principalpixel offset: ({px_offset:.2f}, {py_offset:.2f}) px')

# Precompute undistortion maps once for real-time video streams
new_K, _ = cv2.getOptimalNewCameraMatrix(K, dist, (w, h), alpha=0.0, newImgSize=(w, h))
map1, map2 = cv2.initUndistortRectifyMap(K, dist, None, new_K, (w, h), cv2.CV_16SC2)
# Inside runtime loop: undistorted = cv2.remap(raw_frame, map1, map2, cv2.INTER_LINEAR)

Three additional optical checks determine whether vision encoders or YOLO detectors transfer cleanly from simulation:

  • Lock auto-exposure (AE) and auto-white-balance (AWB): As the robot arm enters the frame, automatic exposure shifts brightness and alters shutter-speed motion blur unpredictably. Fix exposure time, gain, and white-balance temperature manually through V4L2 or the camera SDK.
  • Avoid per-frame cv2.undistort() overhead: Per the OpenCV 4.x documentation, cv2.undistort() recomputes pixel mappings on every call; precomputing cv2.initUndistortRectifyMap() once and calling cv2.remap() keeps real-time latency minimal.
  • Photometric and sensor noise augmentation: Simulated frames lack read noise and shutter blur. When training YOLO detectors or visuomotor backbones on rendered frames, pair the color-space jitter parameters documented in Ultralytics Training Augmentation Settings (hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, mosaic) with mild Gaussian sensor noise and motion blur proportional to end-effector speed.

Axis 2: End-to-End Control Latency Measurement and FIFO Delay Modeling

When optics match accurately yet the physical arm overshoots targets or enters sustained joint oscillation, end-to-end control latency is frequently the hidden root cause. Standard simulation loops assume zero delay between rendering frame tt and executing action ata_t, whereas real hardware accumulates three sequential delays:

ttotal=tcam+tinfer+tact,d=round ⁣(ttotalΔtctrl)t_{\text{total}} = t_{\text{cam}} + t_{\text{infer}} + t_{\text{act}}, \qquad d = \mathrm{round}\!\left(\frac{t_{\text{total}}}{\Delta t_{\text{ctrl}}}\right)

Here tcamt_{\text{cam}} covers exposure plus USB/CSI transport, tinfert_{\text{infer}} covers preprocessing and neural network forward pass, and tactt_{\text{act}} covers fieldbus transmission (CAN, RS-485, or serial) plus servo response time. Measure ttotalt_{\text{total}} directly by sending a known step command while logging timestamps and counting the elapsed time until the first camera frame displays joint motion. At a 25 Hz control rate (Δtctrl=40 ms\Delta t_{\text{ctrl}} = 40\text{ ms}), a 60–100 ms physical delay translates to 1–3 full control steps.

Model this lag explicitly during policy training and when validating synthetic pipelines like the MuJoCo scripted demonstrator workflow. In Python/MuJoCo, a collections.deque FIFO ring buffer delays actions or observations by integer control steps. In NVIDIA Isaac Lab, the Actuators documentation provides DelayedPDActuatorCfg, which uniformly samples an environment-level command lag in physics steps from [min_delay, max_delay] at reset using an internal circular buffer.

from collections import deque
import numpy as np

class ActionDelayBuffer:
    """Models measured control loop lag as a fixed-step FIFO queue."""
    def __init__(self, delay_steps: int, default_action: np.ndarray):
        self.delay_steps = max(0, int(delay_steps))
        self.queue = deque(
            [default_action.copy() for _ in range(self.delay_steps + 1)],
            maxlen=self.delay_steps + 1,
        )

    def push_and_pop(self, cmd: np.ndarray) -> np.ndarray:
        self.queue.append(cmd.copy())
        return self.queue[0]

Center the simulator delay on the measured step count dd and randomize only the observed jitter window (typically ±1 control step) rather than masking latency by artificially lowering PID gains.

Both friction and inertial baselines can be measured on a workbench without specialized lab instruments.

  • Axis 3 — Inclined-plane slip test (μs=tan⁡θ\mu_s = \tan\theta): Place the manipulation object on a sample of the actual tabletop surface and tilt one edge slowly until sliding begins. Averaging five readings of the critical slip angle θ\theta yields the static friction coefficient μs=tan⁡θ\mu_s = \tan\theta (for example, θ=26∘\theta = 26^\circ gives μs≈0.49\mu_s \approx 0.49). In the MuJoCo XML Reference, model.geom_friction stores a three-element tuple (sliding, torsional, rolling) per geometry; assign the measured baseline to the sliding component and calibrate torsional friction on soft gripper pads where in-grasp rotation matters.
  • Axis 4 — Weighing links, harnesses, and end-effector payloads: CAD exports routinely omit fasteners, camera brackets, wiring looms, and 3D-printed finger adapters. Furthermore, the MuJoCo documentation notes that any body lacking an explicit <inertial> tag receives an inferred mass computed from geometry volume times water density (1000 kg/m³), which severely distorts lightweight hollow links or dense metal actuators. Weigh the actual end-effector assembly and target objects on a digital scale, update model.body_mass and center-of-mass offsets model.body_ipos, and only then add small per-episode variation.

In NVIDIA Isaac Lab, the MDP Events API applies calibrated ranges across parallel environments using EventTermCfg with mdp.randomize_rigid_body_material (configured via static_friction_range, dynamic_friction_range, restitution_range, and PhysX num_buckets) and mdp.randomize_rigid_body_mass (operation="add" or "scale").

# 1) MuJoCo reset-time randomization centered on measured baselines
rng = np.random.default_rng(42)
base_slide_mu = 0.49
base_obj_mass = 0.145  # kg (measured on digital scale)

model.geom_friction[cube_geom_id, 0] = base_slide_mu * rng.uniform(0.85, 1.15)
model.body_mass[cube_body_id] = base_obj_mass * rng.uniform(0.90, 1.10)

# 2) NVIDIA Isaac Lab EventTermCfg setup
from isaaclab.envs import EventTermCfg
from isaaclab.managers import SceneEntityCfg
import isaaclab.envs.mdp as mdp

object_friction = EventTermCfg(
    func=mdp.randomize_rigid_body_material,
    mode="startup",
    params={
        "asset_cfg": SceneEntityCfg("cube", body_names=".*"),
        "static_friction_range": (0.42, 0.56),
        "dynamic_friction_range": (0.38, 0.52),
        "restitution_range": (0.0, 0.05),
        "num_buckets": 64,
    },
)

eef_mass = EventTermCfg(
    func=mdp.randomize_rigid_body_mass,
    mode="reset",
    params={
        "asset_cfg": SceneEntityCfg("robot", body_names="wrist_link"),
        "mass_distribution_params": (-0.05, 0.05),
        "operation": "add",
    },
)

Cost-Versus-Impact Prioritization Matrix for Domain Randomization Parameters

Changing all parameters simultaneously hides which fix actually improved hardware transfer. The table below orders Sim-to-Real calibration and randomization tasks by implementation cost versus real-world impact:

PriorityAxis & ParameterBaseline Measurement MethodImplementation CostSim2Real ImpactRecommended Randomization Strategy
1Control & observation latency (deque / DelayedPDActuatorCfg)Timestamp delta from step command to first observed motion frameLow (~20 lines of code)Very high (prevents phase lag & oscillation)Measured step count with ±1 step jitter
2Camera intrinsics (K, dist) & AE/AWB lockCheckerboard cv2.calibrateCamera() + manual driver lockLow (one-time setup)Very high (fixes 3D projection scale)Keep intrinsics fixed; jitter extrinsics ±5 mm / ±1.5°
3Lighting, color temperature & sensor noise (hsv_h/s/v, blur)Ambient lighting check + manual exposure lockLow (training augmentation)High (vision encoder robustness)Color-safe HSV jitter, exposure gain, mild noise
4Surface friction (geom_friction, randomize_rigid_body_material)Inclined-plane slip test (μs=tan⁡θ\mu_s = \tan\theta)Low (benchtop test)High (reduces grasp slip & push errors)Narrow scale interval around measured μs\mu_s
5Link/object mass & CoM (body_mass, body_ipos)Digital scale weighing including brackets & harnessesMedium (disassembly/weighing)Medium–high (dynamic & payload tasks)Fix CAD omissions first, then small add/scale
6Actuator stiffness & damping (kp, kd, joint friction)Step-response overshoot and settling-time loggingHigh (system ID required)Medium (tight trajectory tracking)Match step response before adding minor spread

Work down the matrix sequentially, running short hardware evaluation rollouts after locking each priority tier. Eliminating latency and optical bias first resolves the majority of catastrophic transfer failures, leaving friction and mass randomization to handle genuine physical uncertainty without sacrificing task accuracy.

Common mistakes

  • Leaving MuJoCo’s default fovy=45 uncalibrated while expanding lighting randomization to compensate for mis-scaled perspective projections.
  • Assuming zero-latency observations and commands during simulation training, causing joint oscillation when deployed behind a 30–80 ms real hardware pipeline.
  • Omitting <inertial> tags in MJCF so MuJoCo infers body mass from water density (1000 kg/m³), skewing manipulator dynamics before randomization even starts.
  • Calling cv2.undistort() on every live video frame instead of precomputing remap tables once via cv2.initUndistortRectifyMap() and applying cv2.remap().

Pre-flight checklist

  • Camera optical frame conventions (camera_link_optical) and real intrinsics (K, distortion coefficients) match the simulation camera.
  • Auto-exposure (AE) and auto-white-balance (AWB) are locked manually in the physical camera driver.
  • Total loop latency (capture + inference + actuator lag) is measured in milliseconds, converted to control steps, and modeled in simulation.
  • Tabletop/object sliding friction and mounted end-effector masses are measured physically and written as nominal baseline values.
  • Domain randomization bounds stay centered around measured baselines rather than arbitrary wide intervals.

Frequently asked questions

Which of the four axes should be diagnosed first when a sim-trained policy fails on hardware?
Start with camera optics and frame alignment (Axis 1) followed immediately by end-to-end control latency (Axis 2). If perspective projection is mis-scaled or the control loop lags by two or more steps, tuning surface friction or link mass will not stop the arm from overshooting and oscillating.
Should lens distortion be removed from real camera frames or synthesized inside the simulator?
For fixed-mount tabletop setups, precomputing an undistortion map once with cv2.initUndistortRectifyMap() and running cv2.remap() on live frames keeps the pipeline simple and closely aligned with an ideal pinhole simulator. For wide-angle fisheye lenses where cropping loses workspace edges, adding distortion post-processing to simulated renders is preferable.
How do you bridge photometric differences when transferring YOLO or vision encoders trained on simulated images?
Lock the physical camera’s white balance and exposure first, match simulated light color temperature roughly to the workspace, and apply color-space jitter (hsv_h, hsv_s, hsv_v), weak Gaussian sensor noise, and directional motion blur during training. Lower or zero hsv_h if object color distinguishes target classes.

Sources & verification

  1. OpenCV 4.x Documentation — Camera Calibration Tutorial
  2. MuJoCo Documentation — MJCF XML Reference (<camera>, geom_friction, body_mass)
  3. NVIDIA Isaac Lab Documentation — MDP Events (randomize_rigid_body_material, randomize_rigid_body_mass)
  4. NVIDIA Isaac Lab Documentation — Actuators (DelayedPDActuatorCfg)
  5. Ultralytics Documentation — YOLO Training Augmentation Settings

Last verified: