Point order is part of the data
imagePoints[i] must observe objectPoints[i]. Swapping symmetric points can produce a geometrically consistent but semantically incorrect pose.
2D–3D Correspondence & Perspective-n-Point
Given a camera model and model-point/image-pixel correspondences, PnP recovers the rotation and translation from object or world coordinates to the camera. System performance depends on correspondence correctness, geometric observability, RANSAC design, and a consistent imaging model in final optimization, beyond the solver name alone.
Problem Contract
This site uses right-handed frames, column vectors, and the OpenCV optical frame. Given object-frame 3D points Pi, corresponding pixels pi, intrinsics K, and distortion D, PnP estimates ^C R_O and ^C t_O so that transformed model points project back to the observations through the same camera model.
There are 6 unknowns, but rotation has nonlinear orthogonality constraints; simply counting two equations per point is insufficient.
Three known interpoint distances and three camera bearings define the minimal problem, which usually has multiple discrete candidates.
Practical APIs often require or recommend a fourth correspondence to validate and rank P3P candidates; check point-count conventions for each API.
More well-distributed correspondences provide redundancy for robust estimation, weighting, and nonlinear optimization.
Where Correspondences Come From
Correspondences may come from fiducials, feature matches, semantic keypoints, or dense object coordinates. Their noise, correlations, spatial layouts, and failure modes differ, calling for different sampling, weighting, and diagnostics.
| Correspondence sources | 3D side | 2D side | Strengths | Main risks |
|---|---|---|---|---|
| Semantic keypoints | Predefined CAD corners, holes, or axis endpoints | Network heatmaps or coordinate regression | Clear semantics; few correspondences | Occlusion, swapped symmetric points, concentrated layouts |
| Local feature matching | 3D features from SfM / textured CAD models | SIFT, SuperPoint, or foundation-model features | Suitable for camera relocalization and textured objects | Repeated textures and mismatches require robust estimation |
| Dense object coordinates | CAD / NOCS coordinates for each foreground pixel | Pixel grids or sampled foreground points | Many correspondences and broad coverage; suitable for learned systems | Neighboring pixel errors are correlated; count does not equal independent information |
| Fiducials / planar boards | Known square corners or calibration-board coordinates | Subpixel corner detection | High precision and controlled engineering conditions | Strictly coplanar; often two pose candidates |
| Rendering / template matching | Surface points or silhouettes under candidate poses | Observed edges, masks, or feature locations | Can be combined with iterative refinement | Correspondences change with pose, making this an alternating optimization problem |
imagePoints[i] must observe objectPoints[i]. Swapping symmetric points can produce a geometrically consistent but semantically incorrect pose.
Dense coordinate errors are highly correlated locally; sample, cluster, or weight by predicted uncertainty.
A few points spread across object faces and image regions can be more stable than many points concentrated locally.
Self-occlusion, truncation, and external occlusion change the available point set; training and inference should use consistent visibility semantics.
Solver Taxonomy
Choose a solver by minimal sample size, 3D layout, need for multiple solutions, RANSAC use, and subsequent refinement. A single benchmark's mean speed is insufficient.
| Solvers | Point count | Geometry | Candidates | Typical role | Cautions |
|---|---|---|---|---|---|
| P3P / AP3P | 3 in theory; common APIs use a 4th point to disambiguate | Noncollinear minimal set | Up to 4 candidates | RANSAC hypothesis generation; AP3P is a more efficient and stable algebraic implementation | Enumerate candidates and rank using extra points, positive depth, and residuals |
| EPnP | n ≥ 4 | General points; also supports planar configurations | Usually returns one | O(n) noniterative general initialization, commonly used with many correspondences | Nonlinear refinement remains advisable with noise, small samples, or ill-conditioned layouts |
| SQPnP | n ≥ 3 | General and coplanar points | Can return multiple optimal candidates | Fast, globally optimal general-purpose solver | Global optimality applies to its objective; it does not fix incorrect correspondences, incorrect K, or object-symmetry ambiguity |
| IPPE | n ≥ 4 | Must be coplanar | Explicitly returns 2 | Planar targets, AR markers, calibration boards | The two solutions can have similar residuals for small, nearly frontal targets |
| IPPE_SQUARE | Exactly 4 points | Square with a prescribed point order | Explicitly returns 2 | Dedicated fast solution for square markers | Size, origin, and corner order must exactly match the API specification |
| ITERATIVE / LM | Usually n ≥ 4; initialization requirements depend on the API | General or coplanar points | Converges to a local solution depending on initialization | Minimizes pixel reprojection error; often used for final refinement | Not a global initializer; starting pose, robust loss, and parameterization affect convergence |
With many mismatches, propose candidates quickly from small samples, then score against all correspondences.
Generate a general initial pose from many points without obvious outliers; still check positive depth and refine.
Retain both candidates explicitly, rather than letting a generic single-solution API silently choose the wrong branch.
Minimize reprojection error from a trusted initial pose and inlier set, incorporating weights, robust kernels, or priors.
Interactive Lab
The first view shows how pixel residuals and thresholds form a consensus set; the second computes exact RANSAC budgets for different minimal sample sizes; the third compares spatial, planar, nearly collinear, and concentrated layouts. The lab separates solver implementation from the robust-estimation logic shared by PnP methods.
Interactive · PnP & Robust Estimation
Consensus
Residual
Coverage
Pose contract
One draw
Required
Current budget
Verdict
RANSAC Is a Pipeline
The standard pipeline combines minimal-set hypotheses, full-data consensus, adaptive budgets, local optimization, and refitting with all inliers. Thresholds, sample size, and degeneracy checks jointly control robustness and speed.
Randomly select s points from all 2D–3D correspondences; reject duplicates, nearly collinear sets, and clearly ill-conditioned layouts before forming a sample.
P3P/IPPE may return multiple poses. Check rotation validity, positive depth, and finite values for every candidate.
Compute reprojection residuals with the same K, distortion model, and pixel coordinates. Form a consensus set with threshold τ, optionally incorporating confidence or covariance.
Rank by inlier count, truncated cost, or an M-estimator; estimate the required iterations from the best current inlier ratio and stop early when appropriate.
Do not use a minimal-set solution as the final result. Refit with all inliers, update the inlier set, then apply LM/VVS or BA-style refinement.
Log inlier count/ratio, RMS/quantiles, image coverage, minimum depth, candidate separation, and the termination reason.
Degeneracy & Ambiguity
Strictly planar targets are solvable through a homography or IPPE, but often require handling two candidates. Nearly collinear points lack key directional constraints. Concentrated points may be full-rank yet amplify pixel noise into large pose errors through poor conditioning.
Check the second eigenvalue of the centered 3D point covariance, or triangle area; adding points on the same line does not help.
For frontal, distant, or small targets, reprojection errors can be similar. Use temporal information, noncoplanar points, or task priors to disambiguate.
Expanding the 3D baseline and image convex hull is usually more effective than increasing point count alone, especially for out-of-plane rotation and depth.
If observations cannot distinguish two model points, output equivalent poses or multiple hypotheses, or use symmetry-aware scoring rather than forcing a unique label.
Refinement & Uncertainty
Final optimization should use the projection function consistent with the observations, optionally adding robust losses, keypoint covariances, pose priors, and temporal priors. It improves local accuracy but cannot automatically recover from an incorrect branch or severely wrong correspondences.
The optimization Jacobian's spectrum reveals weakly constrained pose directions; a small residual does not make every degree of freedom trustworthy.
For planar or symmetric scenes, retain multiple candidates and scores so tracking, depth, or robot tasks can disambiguate later.
Distant small objects may have good reprojection but inaccurate depth. Grasping should also evaluate TCP, collision, and approach-direction errors.
Across Application Domains
Model points are in the object frame; the output is CTO. Often combined with detection, segmentation, keypoint, or dense object-coordinate networks.
Matching 3D map points to current-frame features yields CTW; trajectory output usually inverts it to WTC.
PnP supplies a visual relative pose; hand–eye extrinsics must convert it to the base / end-effector frame, with consistent meters, millimeters, and timestamps.
Square markers suit IPPE_SQUARE; rendering still requires candidate disambiguation, temporal filtering, and OpenCV-to-graphics frame conversion.
Engineering recipe · OpenCV Python
ok, rvec, tvec, inliers = cv2.solvePnPRansac(
object_points, image_points, K, dist_coeffs,
iterationsCount=1000,
reprojectionError=3.0,
confidence=0.999,
flags=cv2.SOLVEPNP_AP3P,
)
if ok and inliers is not None and len(inliers) >= 4:
ids = inliers[:, 0]
rvec, tvec = cv2.solvePnPRefineVVS(
object_points[ids], image_points[ids],
K, dist_coeffs, rvec, tvec,
) Explicitly check float32/float64, N×3, N×2, and contiguous memory; squeezing a single point must not break array shapes.
Planar or minimal problems require solvePnPGeneric to enumerate candidates before ranking them with task information.
Reproject and log inlier quantiles, convex hull, minimum Z, det(R), and rotation/translation differences between candidates.
Debug Protocol
PnP errors often arise in preprocessing or postprocessing: swapped point order, stale K after resizing, mixed distortion states, incorrect CAD units, or reversed output direction. Visual reprojection and staged checks are more effective than blindly changing flags.
If even ground truth misses imagePoints, check point order, K/D, image transforms, frames, and annotations before PnP.
A consistent global offset suggests a principal-point/crop error; radial edge residuals suggest distortion; a few long arrows suggest mismatches.
OpenCV rvec/tvec map model points into the camera. For camera pose, use Rᵀ and −Rᵀt, rather than negating t alone.
Most visible model points should have Z > 0. Reject negative-depth candidates; explain cases with few visible points using crop and occlusion information.
Apply SVD to centered 3D points and compute the image convex hull. Many concentrated inliers can still provide weak constraints.
Obtain all candidates for planar and P3P cases; an incorrect branch is not a small local error that extra LM iterations will necessarily cross.
Hold inputs, inlier sets, refinement, and output direction fixed before comparing speed, failure rate, and task error.
Next geometry topic · 07