Module contents
Lesson 22 of 33Core 110 min

Pose estimation: 6D objects and human bodies

Estimate 6D object pose using PnP and compare correspondence, regression and render-and-compare methods. Study continuous rotation representations, human keypoint heatmaps and pose metrics.

After this lesson you can

  • Implement EPnP with RANSAC and refine pose by reprojection error.
  • Compare correspondence, direct regression and render-and-compare 6D pose methods.
  • Explain rotation representation discontinuities and use a 6D representation.
  • Train a heatmap keypoint regressor and decode with subpixel precision.
  • Calculate ADD(-S), PCK and OKS and explain treatment of symmetric objects.

Before you start

Where is it, and how is it oriented?

To grasp a box, knowing it is in the image is insufficient: its position and orientation relative to the robot are needed. 6D object pose combines translation t∈R3t\in\mathbb R^3 and rotation R∈SO(3)R\in SO(3); “6D” here counts degrees of freedom, not the six-number rotation representation seen later. Imitating a human demonstration also requires relating joints, body, time, and the robot frame. A wrist pixel does not by itself determine safe 3D motion.

One approach predicts correspondences between known object points and pixels and computes a geometric pose. Another directly regresses pose from an image; its output depends on training, framing, and intrinsics. A third renders a hypothesis and compares appearance or geometry to refine it: FoundationPose is a modern example of rendering-based estimation and tracking. Each family must handle occlusion, model errors, and symmetries; this classification does not guarantee one is always superior.

PnP and consensus

In perspective-n-point (PnP), points XiX_i in the object frame, pixels uiu_i, and calibration KK are known. We seek R,tR,t minimizing pixel residuals ui−π(K(RXi+t))u_i-\pi(K(RX_i+t)). A solver can return multiple solutions, particularly with few points or planar geometry. Check positive depth, point configuration, and reprojection error, and do not confuse a good 2D fit with guaranteed 3D accuracy.

EPnP expresses each point as an affine combination of four virtual control points. Projection equations form a matrix with 12 columns; singular vectors associated with small values describe candidates for camera-frame controls. Known distances between controls constrain their coefficients and rigid alignment recovers pose. The original method also handles planar cases; our educational implementation restricts controls to noncoplanar sets and uses six or more points.

RANSAC repeats hypotheses with subsets and selects consensus by reprojection threshold; then Levenberg–Marquardt refines it. The threshold is in pixels and should relate to noise and calibration. Consensus can be incorrect when false correspondences are coherent. Coplanar points, symmetry, and weak perspective can leave several plausible hypotheses, so retain uncertainty and use more views or depth information.

InteractivePnP ambiguities

Four corners feed IPPE. Adding a fifth point refines both initial hypotheses using all observations and they may converge to the same pose. RMS averages both coordinates of each point; noise is a fixed scaled realization.

Tilt
Image noise
Point outside plane
Coordinate RMS A0.612 px
Coordinate RMS B2.461 px
Synthetic planar object; both IPPE hypotheses and their errors were computed with OpenCV. A fifth point outside the plane allows both hypotheses to be refined, and they may coincide; noise is a fixed scaled realization.

Rotations and continuity

The continuous rotation representation proposed by Zhou and colleagues stores the first two columns of RR. A network emits a,b∈R3a,b\in\mathbb R^3 and Gram–Schmidt produces

r1=a∥a∥,r2=b−(r1⊤b)r1∥b−(r1⊤b)r1∥,r3=r1×r2,R=[r1 r2 r3].r_1=\frac{a}{\|a\|},\quad r_2=\frac{b-(r_1^\top b)r_1}{\|b-(r_1^\top b)r_1\|},\quad r_3=r_1\times r_2,\quad R=[r_1\ r_2\ r_3].

The encoder R↦(r1,r2)R\mapsto(r_1,r_2) is continuous. The decoder is continuous where a≠0a\ne0 and a,ba,b are not parallel; it is undefined for degenerate outputs and code must detect them. No claim is made that a valid continuous decoder exists on all of R6\mathbb R^6. The representation is redundant, but avoids a target jump when traversing a full turn.

A unit quaternion qq and −q-q represent the same rotation. Choosing a canonical sign creates a discontinuity; a loss minimizing over both signs avoids penalizing that equivalence, but does not make a global sign choice continuous. To see the obstacle, follow a rotation about an axis from 0 to 2π2\pi: its continuous lift starts at qq and ends at −q-q, although the two endpoint rotations coincide. A unique continuous choice would need both values at the same point, a contradiction. The paper also analyzes the general case of continuous representations of dimension four or less under its topological definition.

InteractiveDiscontinuities when regressing rotations
The same object rotated 0°
Components: angle / πGeodesic error (degrees, scale 0 to 180)0°180°360°

Error curves: Euler red, quaternion orange and 6D blue; highlighted: Euler. Each MLP receives sine and cosine of rotation and was trained on the same 256 rotations. These are training errors, not a generalization evaluation.

0
Representation
Target value0.00 rad
Measured network error0.70°
Mean angular error2.76°
Three MLPs actually trained on 256 single-axis rotations, using sine and cosine inputs. Lower curves are geodesic errors on those same rotations; they are not a benchmark or measure of generalization.

The plot shows an Euler choice with principal angle and a quaternion with nonnegative scalar component. Both conventions jump at 180°. A network can follow a smooth quaternion path if sign choice may change, but there is no unique continuous choice for every rotation. In this small experiment mean training angular error was 2.761°, 1.165° and 0.090° for Euler, quaternion, and 6D; results depend on architecture, loss, and data.

Heatmaps and bodies

Heatmap regression assigns a distribution or intensity per keypoint. During training a Gaussian target is usually centered at the projection and a heatmap loss minimized. Integer argmax quantizes to the grid; a normalized average or local neighbor fit can give subpixel coordinates, although it does not eliminate bias or uncertainty. A global average sensitive to background and cropping may be displaced; quadratic log fitting is exact for an ideal noiseless Gaussian with neighbors available, not arbitrary network output.

InteractiveHeatmaps and subpixel accuracy

White ring: truth; cyan cross: argmax; green: normalized-map average; yellow: neighbor fit on the logarithm. The average may shift near the edge due to truncation.

4.35
6.65
1.0
Argmax error0.495 px
Soft average error0.000 px
Log-neighbor error0.000 px
Ideal Gaussian sampled on an 11×11 grid. The average uses the normalized map, and refinement fits three logarithmic values per axis; it is compared with known position.

In human pose estimation, a top-down system detects people, crops each, and predicts joints; a bottom-up system detects points in the image and groups them by person. OpenPose uses affinity fields to associate parts; Simple Baselines is a top-down heatmap reference. Overlapping people, hidden points, and identity changes affect both approaches.

2D pose does not determine absolute depth or human scale. Parametric body models can fit shape, joints, and projection using priors, but those priors do not replace observations under occlusion. Imitation needs calibration, temporal association, frame transformation, correspondence between human and robot bodies, and motion constraints; the wrist trajectory below is an exploratory 2D signal, not a demonstration ready for control.

Metrics and symmetries

Pose metrics should reflect the task. ADD averages ∥RXi+t−(R^Xi+t^)∥\|RX_i+t-(\hat R X_i+\hat t)\| over model points with fixed correspondence. ADD-S replaces each distance with the nearest neighbor distance in the other set: it can accept equivalent poses of symmetric objects, but may underestimate errors for discrete models or similar surfaces. BOP uses symmetry- and visibility-aware metrics such as MSSD, MSPD and VSD; it is not synonymous with ADD-S.

PCK counts the fraction of points whose 2D distance falls below a threshold normalized by an agreed scale, such as box size. OKS combines per-joint error exponentials normalized by person scale and point-specific tolerance, excluding points according to the benchmark’s visibility convention. A single PCK or OKS does not specify scale, threshold, or included joints: report these details when comparing.

With errors did_i in pixels, scale ss, inclusion indicator viv_i and tolerance kik_i, one form of these metrics is

PCK⁡=∑ivi1[di<τs]∑ivi,OKS⁡=∑iviexp⁡(−di2/(2s2ki2))∑ivi.\operatorname{PCK}=\frac{\sum_i v_i\mathbf1[d_i<\tau s]}{\sum_i v_i},\qquad \operatorname{OKS}=\frac{\sum_i v_i\exp(-d_i^2/(2s^2k_i^2))}{\sum_i v_i}.

Constants and visibility treatment depend on protocol; person scale and kik_i must match the benchmark’s specific definition. Both metrics above require at least one included point and positive scale.

For an ideal handleless cup, an axial rotation may leave the surface indistinguishable while fixed-index ADD penalizes it. If the handle exists and is observable, that rotation is no longer a symmetry of the complete object. The symmetry set must come from the model and task definition; a real cup does not become symmetric merely because its handle is hidden.

Lab: EPnP and metrics from scratch

We generate 60 noncoplanar points, 0.5 px noise, and 12 altered correspondences. The solver uses four controls, four singular vectors, distance constraints, and rigid alignment; it tries signs and refines using LM. This educational version does not reproduce every initialization or the original EPnP planar case. In Pyodide it finds 48 inliers, no accepted outliers, rotation error 0.248° and translation error 0.000762 m for this seed. RANSAC does not promise to recover that solution in every scene.

[ ]EPnP with RANSAC and refinementBrowser
import numpy as np
from scipy.optimize import least_squares
from scipy.spatial.transform import Rotation

def align(A,B):
    a=A.mean(0);b=B.mean(0);U,_,V=np.linalg.svd((A-a).T@(B-b));D=np.eye(3);D[2,2]=np.linalg.det(V.T@U.T)
    R=V.T@D@U.T;return R,b-R@a
def project(X,R,t,K):
    q=(R@X.T).T+t;p=(K@q.T).T
    return p[:,:2]/p[:,2,None]
def epnp(X,uv,K):
    X=np.asarray(X,float);uv=np.asarray(uv,float)
    if len(X)<6:raise ValueError('esta versión requiere al menos seis puntos')
    center=X.mean(0);_,s,Vt=np.linalg.svd(X-center,full_matrices=False)
    if s[-1]<1e-8:raise ValueError('esta versión requiere puntos no coplanares')
    controls=np.vstack([center,center+Vt*s[:,None]/np.sqrt(len(X))]);
    b=np.linalg.solve((controls[1:]-center).T,(X-center).T).T;alpha=np.c_[1-b.sum(axis=1),b]
    xy=(np.linalg.inv(K)@np.c_[uv,np.ones(len(uv))].T).T;xy=xy[:,:2]/xy[:,2,None]
    M=np.zeros((2*len(X),12))
    for j in range(4):
        M[0::2,3*j]=alpha[:,j];M[0::2,3*j+2]=-alpha[:,j]*xy[:,0]
        M[1::2,3*j+1]=alpha[:,j];M[1::2,3*j+2]=-alpha[:,j]*xy[:,1]
    _,_,V=np.linalg.svd(M,full_matrices=True);basis=V[-4:].reshape(4,4,3)
    pairs=[(i,j) for i in range(4) for j in range(i+1,4)]
    d=np.array([basis[:,i,:]-basis[:,j,:] for i,j in pairs]);dist=np.array([np.sum((controls[i]-controls[j])**2) for i,j in pairs])
    def fun(beta):return np.sum(np.einsum('pki,k->pi',d,beta)**2,axis=1)-dist
    # Aproximación de una base y refinamiento de las cuatro; prueba ambos signos.
    scale=np.sqrt(np.dot(np.sum(d[:,3,:]**2,axis=1),dist)/np.dot(np.sum(d[:,3,:]**2,axis=1),np.sum(d[:,3,:]**2,axis=1)))
    best=None
    for sign in (1,-1):
        initial=np.array([0.,0.,0.,sign*scale]);beta=least_squares(fun,initial,max_nfev=35).x
        camera=alpha@np.einsum('k,kij->ij',beta,basis);R,t=align(X,camera)
        if np.mean(((R@X.T).T+t)[:,2]>0)<.95:continue
        error=np.mean(np.sum((project(X,R,t,K)-uv)**2,axis=1))
        if best is None or error<best[0]:best=(error,R,t)
    if best is None:raise ValueError('sin solución delante de la cámara')
    return best[1],best[2]
def refine(X,uv,K,R,t):
    def residual(p):return (project(X,Rotation.from_rotvec(p[:3]).as_matrix(),p[3:],K)-uv).ravel()
    p=np.r_[Rotation.from_matrix(R).as_rotvec(),t];v=least_squares(residual,p,method='lm',max_nfev=100).x
    return Rotation.from_rotvec(v[:3]).as_matrix(),v[3:]
def robust(X,uv,K,rng,trials=50,threshold=3.):
    best=np.zeros(len(X),dtype=bool)
    for _ in range(trials):
        ids=rng.choice(len(X),8,replace=False)
        try:R,t=epnp(X[ids],uv[ids],K)
        except (ValueError,np.linalg.LinAlgError):continue
        err=np.linalg.norm(project(X,R,t,K)-uv,axis=1);mask=err<threshold
        if mask.sum()>best.sum():best=mask
    if best.sum()<8:raise ValueError('consenso insuficiente')
    R,t=epnp(X[best],uv[best],K);R,t=refine(X[best],uv[best],K,R,t)
    return R,t,best
def test():
    rng=np.random.default_rng(9);X=rng.uniform(-.2,.2,(60,3));R=Rotation.from_euler('xyz',[20,-25,12],degrees=True).as_matrix();t=np.array([.03,-.02,1.2]);K=np.array([[500,0,320],[0,500,240],[0,0,1.]])
    uv=project(X,R,t,K)+rng.normal(0,.5,(len(X),2));bad=rng.choice(len(X),12,replace=False);uv[bad]=rng.uniform([150,100],[500,380],(12,2));R1,t1,mask=robust(X,uv,K,rng)
    print('inliers:',mask.sum(),'atípicos aceptados:',np.intersect1d(bad,np.flatnonzero(mask)).size,'error rotación grados:',np.degrees(Rotation.from_matrix(R1@R.T).magnitude()),'error traslación m:',np.linalg.norm(t1-t))
test()

The next cell implements Gram–Schmidt and ADD/ADD-S. A discrete 36-point circle rotated 90° gives ADD 0.1414 m and ADD-S near zero: its symmetry is known and exactly matches the sampling.

[ ]Rotations and surface distancesBrowser
import numpy as np
from scipy.spatial.transform import Rotation

def rotation_from_6d(x):
 a=np.asarray(x[:3],dtype=float);b=np.asarray(x[3:],dtype=float)
 if np.linalg.norm(a)<1e-9:raise ValueError('primer vector nulo')
 r1=a/np.linalg.norm(a);v=b-np.dot(r1,b)*r1
 if np.linalg.norm(v)<1e-9:raise ValueError('vectores paralelos')
 r2=v/np.linalg.norm(v);return np.column_stack([r1,r2,np.cross(r1,r2)])
def add(points,R,t,Rhat,that):
 a=(R@points.T).T+t;b=(Rhat@points.T).T+that
 return np.linalg.norm(a-b,axis=1).mean()
def add_s(points,R,t,Rhat,that):
 a=(R@points.T).T+t;b=(Rhat@points.T).T+that
 return np.linalg.norm(a[:,None]-b[None,:],axis=2).min(axis=1).mean()
angle=np.linspace(0,2*np.pi,36,endpoint=False);circle=np.c_[.1*np.cos(angle),.1*np.sin(angle),np.zeros(36)];eye=np.eye(3);zero=np.zeros(3);turn=Rotation.from_euler('z',90,degrees=True).as_matrix()
print('traslación 1 cm ADD (m):',add(circle,eye,zero,eye,np.array([.01,0,0])))
print('giro simétrico ADD/ADD-S (m):',add(circle,eye,zero,turn,zero),add_s(circle,eye,zero,turn,zero))
q=rotation_from_6d([1,.1,0,.1,1,.1]);print('error ortogonalidad:',np.max(np.abs(q.T@q-eye)),'determinante:',np.linalg.det(q))

Local lab: object and person

A synthetic object with eight known points is rendered in MuJoCo with 400 training poses and 100 held out. A shared CNN learns heatmaps and a direct 6D rotation plus translation output; PnP uses the eight predicted points and known intrinsics. Even hidden corners are supervised, possible because the simulator provides pose. In one 50-epoch RTX 3060 run, mean point error was 2.231 px. Median rotation/translation errors were 22.929°/0.0289 m for direct regression and 21.426°/0.0272 m for PnP, which returned pose in all 100 cases. One object, limited pose range, and the same scene do not demonstrate generalization or robustness to real occlusion.

In an environment with NumPy, SciPy, mujoco==4.0.1, OpenCV and PyTorch, run these cells in order. Both outputs share encoder and data; they are not independent models. Time depends on GPU and load. The heatmap decoder uses a local average in a three-by-three window, different from the ideal log-quadratic fit in the figure.

[ ]Object views in MuJoCoLocal GPU
import numpy as np
import mujoco
from scipy.spatial.transform import Rotation

def object_dataset(count=500,seed=22):
 rng=np.random.default_rng(seed);size=64;model_points=np.array([[x,y,z] for x in (-.20,.20) for y in (-.14,.14) for z in (-.10,.10)])
 colors=['1 .1 .1 1','.1 1 .1 1','.1 .1 1 1','1 1 .1 1','1 .1 1 1','.1 1 1 1','1 .5 .1 1','.6 .3 1 1']
 dots=''.join(f'<geom type="sphere" pos="{x} {y} {z}" size=".018" rgba="{c}"/>' for (x,y,z),c in zip(model_points,colors))
 xml=f'''<mujoco><visual><global offwidth="64" offheight="64"/></visual><worldbody>
 <light pos="0 1 0" dir="0 0 -1" diffuse=".8 .8 .8" ambient=".4 .4 .4"/><camera name="cam" pos="0 0 0" fovy="50"/>
 <body name="obj"><freejoint/><geom type="box" size=".2 .14 .1" rgba=".65 .55 .4 1" mass="1"/>{dots}</body></worldbody></mujoco>'''
 model=mujoco.MjModel.from_xml_string(xml);data=mujoco.MjData(model);renderer=mujoco.Renderer(model,size,size);f=size/(2*np.tan(np.deg2rad(50)/2));K=np.array([[f,0,32],[0,f,32],[0,0,1.]])
 images=[];uv=[];rot=[];trans=[];flip=np.diag([1,-1,-1])
 for _ in range(count):
  R=Rotation.from_euler('xyz',rng.uniform([-.45,-.45,-.65],[.45,.45,.65])).as_matrix();q=Rotation.from_matrix(R).as_quat();p=np.r_[rng.uniform(-.14,.14,2),rng.uniform(-1.4,-1.0)]
  data.qpos[:3]=p;data.qpos[3:]=[q[3],q[0],q[1],q[2]];mujoco.mj_forward(model,data);renderer.update_scene(data,camera='cam');images.append(renderer.render().copy())
  Rc=flip@R;tc=flip@p;points=(Rc@model_points.T).T+tc;projection=(K@points.T).T;uv.append(projection[:,:2]/projection[:,2,None]);rot.append(Rc);trans.append(tc)
 renderer.close();return np.array(images),np.array(uv),np.array(rot),np.array(trans),model_points,K
images,uv,R,t,points,K=object_dataset()
print('imágenes:',images.shape,'rango de píxeles:',uv.min(),uv.max())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Heatmaps versus direct regressionLocal GPU
import time
import cv2
import numpy as np
import torch
from scipy.spatial.transform import Rotation

torch.manual_seed(22);np.random.seed(22);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
inputs=torch.tensor(images.transpose(0,3,1,2)/255,dtype=torch.float32,device=device)
target_xy=torch.tensor((uv+.5)/4-.5,dtype=torch.float32,device=device);gridy,gridx=torch.meshgrid(torch.arange(16,device=device),torch.arange(16,device=device),indexing='ij')
heat=torch.exp(-((gridx[None,None]-target_xy[:,:,0,None,None])**2+(gridy[None,None]-target_xy[:,:,1,None,None])**2)/(2*1.0**2))
rot6=torch.tensor(R[:,:,:2].transpose(0,2,1).reshape(-1,6),dtype=torch.float32,device=device)
scaled=(t-np.array([0,0,1.2]))/.2;pose=torch.cat([rot6,torch.tensor(scaled,dtype=torch.float32,device=device)],1)
class Model(torch.nn.Module):
 def __init__(self):
  super().__init__();self.enc=torch.nn.Sequential(torch.nn.Conv2d(3,32,5,stride=2,padding=2),torch.nn.ReLU(),torch.nn.Conv2d(32,64,3,stride=2,padding=1),torch.nn.ReLU(),torch.nn.Conv2d(64,64,3,padding=1),torch.nn.ReLU());self.hm=torch.nn.Conv2d(64,8,1);self.pose=torch.nn.Sequential(torch.nn.Flatten(),torch.nn.Linear(64*16*16,128),torch.nn.ReLU(),torch.nn.Linear(128,9))
 def forward(self,x):
  z=self.enc(x);return self.hm(z),self.pose(z)
net=Model().to(device);opt=torch.optim.Adam(net.parameters(),lr=.001);start=time.perf_counter()
for epoch in range(50):
 ids=torch.randperm(400,device=device)
 for batch in ids.split(50):
  hm,pred=net(inputs[batch]);h=torch.sigmoid(hm);loss=((1+25*heat[batch])*(h-heat[batch])**2).mean()+.15*((pred-pose[batch])**2).mean()
  opt.zero_grad();loss.backward();opt.step()
 if epoch in (0,9,24,49):print('época',epoch+1,'pérdida',round(float(loss.detach()),5),flush=True)
if device.type=='cuda':torch.cuda.synchronize()
print('tiempo s:',round(time.perf_counter()-start,2))
with torch.no_grad():hm,pred=net(inputs[400:]);prob=torch.sigmoid(hm).cpu().numpy();pred=pred.cpu().numpy()
pred_xy=[]
for maps in prob:
 xy=[]
 for h in maps:
  yy,xx=np.unravel_index(np.argmax(h),h.shape)
  # Promedio local alrededor del máximo: explícitamente no softargmax global.
  ya,yb=max(0,yy-1),min(16,yy+2);xa,xb=max(0,xx-1),min(16,xx+2);patch=h[ya:yb,xa:xb];Y,X=np.mgrid[ya:yb,xa:xb];mass=patch.sum()
  xy.append([(float((X*patch).sum()/mass)+.5)*4-.5,(float((Y*patch).sum()/mass)+.5)*4-.5])
 pred_xy.append(xy)
pred_xy=np.array(pred_xy);pixel=np.linalg.norm(pred_xy-uv[400:],axis=-1);print('puntos error píxel medio:',round(float(pixel.mean()),3),'mediana:',round(float(np.median(pixel)),3))
def rot6d(x):
 a=x[:3];b=x[3:6]
 if np.linalg.norm(a)<1e-9:raise ValueError('primer vector nulo')
 a=a/np.linalg.norm(a);b=b-a*np.dot(a,b)
 if np.linalg.norm(b)<1e-9:raise ValueError('vectores paralelos')
 b=b/np.linalg.norm(b);return np.column_stack([a,b,np.cross(a,b)])
direct_r=[];direct_t=[];pnp_r=[];pnp_t=[];pnp_count=0
for j in range(100):
 truth=R[400+j];r=rot6d(pred[j]);td=pred[j,6:]*.2+[0,0,1.2]
 direct_r.append(np.degrees(Rotation.from_matrix(r@truth.T).magnitude()));direct_t.append(np.linalg.norm(td-t[400+j]))
 ok,rv,tv,ids=cv2.solvePnPRansac(points,pred_xy[j],K,None,iterationsCount=100,reprojectionError=5.,flags=cv2.SOLVEPNP_EPNP)
 if ok and ids is not None and len(ids)>=4:
  pnp_count+=1;r=cv2.Rodrigues(rv)[0];pnp_r.append(np.degrees(Rotation.from_matrix(r@truth.T).magnitude()));pnp_t.append(np.linalg.norm(tv.ravel()-t[400+j]))
print('directa mediana giro/grados y traslación/m:',round(float(np.median(direct_r)),3),round(float(np.median(direct_t)),4))
print('PnP válidos:',pnp_count,'mediana giro/grados y traslación/m:',round(float(np.median(pnp_r)),3),round(float(np.median(pnp_t)),4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

2D wrist trajectory

The next cell uses pretrained MediaPipe Pose Landmarker Lite on CPU. To reproduce the test, install mediapipe==1.2.3 and opencv-python-headless==5.0.0.93 in a compatible environment and run the cell there; it downloads the official model and the OpenCV example video pinned to a commit. SHA256 is checked before either file is used.

On this machine camera 0 could not be opened. With the first 100 frames of the public video and a fixed crop of one person, there were 86 detections and median right-wrist visibility of 0.6476. Without that crop there were no detections in the test. There are no ground-truth annotations or identity-preservation guarantees; the CSV contains only detected frames, timestamps, normalized full-image coordinates, and visibility. Changing source to webcam processes the local camera if available, without cropping, and writes results to the working directory. An observed trajectory needs validation and calibration before robot use.

[ ]Wrist in video or webcamLocal GPU
from pathlib import Path
from urllib.request import urlretrieve
import hashlib, time
import cv2
import numpy as np
import mediapipe as mp

# Cambia a 'webcam' para intentar cámara 0. 'video' reproduce el ejemplo público.
source='video'
model=Path('pose_landmarker_lite.task');video=Path('vtest.avi')
assets=[(model,'https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task','59929e1d1ee95287735ddd833b19cf4ac46d29bc7afddbbf6753c459690d574a')]
if source=='video':assets.append((video,'https://raw.githubusercontent.com/opencv/opencv/6103e82e10677bbd9fef2169119630ac94f83893/samples/data/vtest.avi','45cddc9490be69345cbdab64ca583be65987e864ca408038e648db99e10516cf'))
for path,url,digest in assets:
 if not path.exists():urlretrieve(url,path)
 if hashlib.sha256(path.read_bytes()).hexdigest()!=digest:raise ValueError(f'hash incorrecto: {path}')
cap=cv2.VideoCapture(str(video) if source=='video' else 0)
if not cap.isOpened():raise RuntimeError('No se pudo abrir la fuente de vídeo')
fps=cap.get(cv2.CAP_PROP_FPS) if source=='video' else None
options=mp.tasks.vision.PoseLandmarkerOptions(base_options=mp.tasks.BaseOptions(model_asset_path=str(model)),running_mode=mp.tasks.vision.RunningMode.VIDEO,num_poses=1)
rows=[];start=time.monotonic();last=-1;processed=0
with mp.tasks.vision.PoseLandmarker.create_from_options(options) as detector:
 for i in range(100):
  ok,bgr=cap.read()
  if not ok:break
  processed+=1;H,W=bgr.shape[:2]
  # Recorte fijo de la persona del ejemplo; sin recorte para webcam.
  x0,y0,x1,y1=(180,180,350,360) if source=='video' else (0,0,W,H)
  crop=bgr[y0:y1,x0:x1];rgb=cv2.cvtColor(crop,cv2.COLOR_BGR2RGB)
  timestamp=int(round(1000*i/fps)) if source=='video' else int((time.monotonic()-start)*1000)
  timestamp=max(last+1,timestamp);last=timestamp
  result=detector.detect_for_video(mp.Image(image_format=mp.ImageFormat.SRGB,data=rgb),timestamp)
  if result.pose_landmarks:
   p=result.pose_landmarks[0][16]
   rows.append((i,timestamp,(x0+p.x*(x1-x0))/W,(y0+p.y*(y1-y0))/H,p.visibility))
cap.release()
if not rows:raise RuntimeError('No se detectó ninguna pose; no se genera trayectoria')
arr=np.asarray(rows);np.savetxt('wrist-demo.csv',arr,delimiter=',',header='frame,time_ms,x_normalized,y_normalized,visibility',comments='')
print('fotogramas procesados:',processed,'detecciones:',len(rows),'visibilidad mediana:',round(float(np.median(arr[:,4])),4))
print('primera detección:',np.round(arr[0],4),'última:',np.round(arr[-1],4))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofOne turn and two signs
Prove: Prove that no global continuous choice of unit quaternion exists for every rotation.
0
Consider a turn from 0 to 2π around a fixed axis and the map from unit quaternions to SO(3).

Step 1 of 3. Which rotations correspond to the endpoints of the turn?

CodeTwo columns for a rotation
Implement rotation_from_6d(x): x contains the three components of a followed by the three of b. Return a 3×3 matrix with orthonormal columns and positive determinant. If a is zero or b is parallel to a with residual norm below 1e-9, raise ValueError.
import numpy as np
def rotation_from_6d(x):
  pass
Shift+Enter to run
Numeric
An estimated pose differs from truth only by 1 cm of translation; rotation is identical. What is ADD in centimeters for four model points?
cm
Quiz
A textured object is partly occluded and several well-identified points remain. What approach uses that information?
Quiz
Why can ADD penalize an equivalent rotation of an ideal handleless cup?
Key idea
Pose combines geometry, representation, and evidence: examine ambiguities, symmetries, and calibration before turning pixels into motion.

Sources: EPnP, Zhou and colleagues, PoseCNN, FoundationPose, OpenPose, Simple Baselines and BOP.