AI Wiki中文/EN

Stereo vision: find the same surface in two images

立体视觉

Derive calibrated depth, build eight-direction SGM, and train a tiny feature cost while testing occlusion and soft-argmin ambiguity.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two views help only if you match the same thing

Hold a finger in front of your face and alternate which eye is open. The finger shifts against the background. Move it farther away and the shift becomes smaller. A stereo camera uses that change in image position to estimate depth. Its difficult question is not just “How far did this pixel move?” but “Which pixel in the other image shows the same surface?”

Stereo vision recovers scene information from different camera viewpoints. This article focuses on calibrated two-view geometry and dense correspondence. The geometry can be exact while a repeated window, a blank wall or a hidden surface still produces the wrong match. A point visible to only one camera has no correct correspondence in the other image.

A useful nonlearned baseline searches along a rectified image row for the patch with the smallest squared appearance difference. It makes the problem inspectable: search range, patch size, occlusion and ambiguity are all explicit. SGM adds pathwise smoothness; learned methods can replace fixed appearance comparisons and add context. Scharstein and Szeliski’s taxonomy distinguishes matching cost, aggregation, optimization and refinement rather than treating a stereo system as one indivisible operation. Four-stage taxonomy

We implement a complete small pipeline with projection, triangulation, an SSD cost volume, eight-direction SGM and left-right checking. A second example learns every parameter of a tiny feature cost and differentiates through soft argmin. All images and training data are synthetic. Some consistency checks pass for the wrong surface, and the program preserves those failures.

Computed disparity-to-depth mapping, consistency false acceptances, a bimodal soft argmin and one feature-cost update. Synthetic examples; not benchmark performance.
Computed disparity-to-depth mapping, consistency false acceptances, a bimodal soft argmin and one feature-cost update. Synthetic examples; not benchmark performance.

Geometry narrows the search; it does not certify the match

From two cameras to an epipolar line

Use the left camera frame as the reference. Let X be a 3D point in that frame, and let R,t transform it to the right camera. With homogeneous pixel coordinates:

pL∼KLX,pR∼KR(RX+t),PL=KL[I∣0],PR=KR[R∣t].p_L\sim K_LX,\qquad p_R\sim K_R(RX+t),\qquad P_L=K_L[I\mid0],\quad P_R=K_R[R\mid t].

The symbol “similar” here means equality up to nonzero homogeneous scale. Intrinsics map camera coordinates to pixels; R,t are a left-to-right coordinate transform, not a camera-center vector copied without changing signs. Coordinates must follow the calibration model, including distortion handling. Camera and triangulation conventions

The two viewing rays and baseline give an epipolar constraint. Define the skew matrix by [t]_x v=t cross v:

pRTFpL=0,F=KR−T[t]×RKL−1.p_R^TFp_L=0,\qquad F=K_R^{-T}[t]_\times R K_L^{-1}.

For a left point other than the epipole, Fp_L gives a line in the right image. The epipole is the projection of the other camera center; there Fp_L is zero and does not define a unique line. Away from this degeneracy, the ideal constraint reduces a 2D correspondence search to a line, but does not say which point on it is correct. With invertible intrinsics, a proper rotation and nonzero translation, F has rank two and is defined up to scale. Our function normalizes it by its Frobenius norm. Epipolar equation

Why is the residual zero? In right-camera coordinates, RX and t span the plane containing RX+t. The vector t cross RX is perpendicular to both, so its dot product with RX+t vanishes. Substitute the two backprojected pixel rays and cancel their nonzero depth factors to obtain the displayed constraint.

Once a correspondence is supplied, linear triangulation stacks four equations. Write P_L^(j) for row j of the left projection matrix, and similarly for the right:

A=[uLPL(3)−PL(1)vLPL(3)−PL(2)uRPR(3)−PR(1)vRPR(3)−PR(2)],AX~≈0.A=\begin{bmatrix} u_LP_L^{(3)}-P_L^{(1)}\\ v_LP_L^{(3)}-P_L^{(2)}\\ u_RP_R^{(3)}-P_R^{(1)}\\ v_RP_R^{(3)}-P_R^{(2)} \end{bmatrix},\qquad A\widetilde X\approx0.

The last right singular vector of A minimizes the algebraic residual under a unit-norm constraint. Divide it by its homogeneous coordinate to obtain a finite point. The implementation rejects a degenerate system, a point at infinity and a point behind either camera, using physically oriented projection matrices. It verifies exact nonrectified synthetic correspondences, but does not claim that this algebraic solution minimizes pixel reprojection error in noisy data. Homogeneous triangulation and output frames

Rectification, disparity and the principal-point offset

Rectification reprojects the views so corresponding epipolar lines are aligned. For horizontal stereo, matched points then have the same vertical coordinate. It is a calibrated change of image geometry, not simply moving one picture until a few features line up. Rectification outputs

Let the right camera center be B units to the right of the left center, with B positive. In the rectified frame t=[−B,0,0]. If the rectified focal lengths are equal:

uL=fX/Z+cxL,uR=f(X−B)/Z+cxR,d=uL−uR=fBZ+cxL−cxR,Z=fBd−(cxL−cxR).u_L=fX/Z+c_{xL},\qquad u_R=f(X-B)/Z+c_{xR},\qquad d=u_L-u_R=\frac{fB}{Z}+c_{xL}-c_{xR},\qquad Z=\frac{fB}{d-(c_{xL}-c_{xR})}.

Here f is in pixels, while B and Z share a length unit. The familiar fB/d form requires equal horizontal principal points. OpenCV’s rectification flag can enforce equal principal points; without it, the offset must remain in the mapping. Resizing pixel coordinates requires consistent changes to focal length, disparity and principal points. P1, P2 and Q matrices

For f=800 and B=0.1, disparities 20 and 5 give depths 4 and 16 when the principal points coincide. If raw disparity is 40 but the principal-point offset is 20, depth is 4; ignoring the offset gives 2. A raw negative disparity may still have positive corrected disparity in the general formula. Our dense matching demonstration is narrower: equal principal points and nonnegative integer disparity candidates.

A first-order propagation of a small disparity standard deviation gives:

∂Z∂d=−fB(d−Δcx)2,σZ≈fB(d−Δcx)2σd.\frac{\partial Z}{\partial d}=-\frac{fB}{(d-\Delta c_x)^2},\qquad \sigma_Z\approx\frac{fB}{(d-\Delta c_x)^2}\sigma_d.

For a one-pixel disparity standard deviation, the two examples give approximately 0.2 and 3.2 depth units. This is a local approximation with calibration held fixed, not an exact finite-error bound. Near zero corrected disparity, the nonlinear mapping becomes especially sensitive. A longer baseline improves this geometric sensitivity for a fixed depth and disparity uncertainty, but also changes overlap and correspondence difficulty.

Build a cost volume before choosing the winner

For rectified images, define a window W around a pixel and compare the left patch with the shifted right patch:

C(y,x,d)=1∣W∣c∑(i,j)∈W∑k=1c(IL(y+i,x+j,k)−IR(y+i,x+j−d,k))2.C(y,x,d)=\frac{1}{|W|c}\sum_{(i,j)\in W}\sum_{k=1}^{c} \left(I_L(y+i,x+j,k)-I_R(y+i,x+j-d,k)\right)^2.

There are c image channels. Our direct implementation stores a cost for each pixel and each integer d from zero through the inclusive maximum disparity. Candidates with incomplete patches receive positive infinity; they do not become cheap zeros. The default window radius is zero, so each cost uses a single pixel. Increasing the window adds support but can mix foreground and background near a depth boundary. SSD also depends on appearance agreement across the cameras. Costs and support windows

A winner-takes-all baseline chooses the least expensive candidate independently. It cannot resolve a textureless region whose candidates all look similar, or a repeated pattern with several equally good matches. A smoothness model adds assumptions about neighboring disparities.

SGM: exact paths, approximate 2D reasoning

One illustrative grid objective combines unary matching costs with pairwise penalties:

E(D)=∑pC(p,Dp)+∑{p,q}∈Eϕ(Dp,Dq),ϕ(a,b)={0a=b,P1∣a−b∣=1,P2∣a−b∣>1.E(D)=\sum_p C(p,D_p)+\sum_{\{p,q\}\in\mathcal E}\phi(D_p,D_q),\qquad \phi(a,b)=\begin{cases}0&a=b,\\P_1&|a-b|=1,\\P_2&|a-b|>1.\end{cases}

In this displayed objective, each undirected edge is counted once. Smaller disparity changes cost P1, larger changes cost P2, with 0≤P1≤P2 in our program. Choosing these penalties trades local appearance against piecewise smooth disparity; it cannot make every real surface obey that prior.

SGM computes dynamic programming costs along several directions. For direction r, let m be the minimum predecessor cost. Its normalized recurrence and the final decision are:

m=min⁡kLr(p−r,k),Lr(p,d)=C(p,d)+min⁡ ⁣{Lr(p−r,d),Lr(p−r,d−1)+P1,Lr(p−r,d+1)+P1,m+P2}−m,S(p,d)=∑rLr(p,d),D^p=arg⁡min⁡dS(p,d).\begin{aligned} m&=\min_k L_r(p-r,k),\\ L_r(p,d)&=C(p,d)+\min\!\left\{ \begin{array}{l} L_r(p-r,d),\\L_r(p-r,d-1)+P_1,\\L_r(p-r,d+1)+P_1,\\m+P_2 \end{array}\right\}-m,\\ S(p,d)&=\sum_rL_r(p,d),\qquad \widehat D_p=\arg\min_d S(p,d). \end{aligned}

Subtracting m removes a label-independent offset, controlling accumulation along a path without changing its label preference. At a boundary we start with the unary cost. If the preceding pixel has no finite state, our implementation restarts that path; this is an explicit invalid-state policy. A pixel with no finite aggregate candidate returns NaN. Ties choose the first candidate in the supplied ordering. Normalized recurrence and path aggregation

Each 1D path has an exact dynamic-programming interpretation. Adding path results and choosing pixelwise minima does not generally solve the displayed 2D objective exactly. The tests use a 2×2 image with cost vectors [0,5,1], [2,7,0], [4,2,3], [7,1,6], P1=2 and P2=3. With all six undirected eight-neighbor edges counted once, exhaustive search finds energy 10 at labels [2,2,2,2]; eight-direction SGM returns a labeling with energy 14. The edge-count convention belongs to this explicit counterexample, not an unqualified reading of every paper’s notation.

Hirschmüller’s 2005 method discusses mutual-information costs, adaptive penalties and later processing. This teaching pipeline uses SSD, fixed penalties and eight directions. It does not reproduce the full original system or its reported benchmark results. Original method and scope

Check correspondence in both directions

Our left and right disparity maps both store nonnegative magnitudes. The left map samples the right image at x−d; the right map samples the left at x+d. With valid integer coordinates, a consistency check is:

∣dL(y,x)−dR(y,x−dL(y,x))∣≤τ.\left|d_L(y,x)-d_R\bigl(y,x-d_L(y,x)\bigr)\right|\leq\tau.

The coordinate sign and disparity-value sign are separate choices. The implementation rejects fractional or negative disparities for this integer checker, checks bounds and finite values, and uses tau=0 by default. It does not perform subpixel interpolation of a reverse map. Bidirectional consistency

Consistency can reject mismatches, but a wrong association may be consistent in both directions. With a nonzero tolerance, it need not enforce one-to-one matching either: left pixels at x=1,d=1 and x=2,d=2 both point to right x=0; a right disparity of 1 allows both through when tau=1. The tests preserve this example instead of calling the check a universal uniqueness guarantee.

Learn a cost, and understand what soft argmin returns

A discrete argmin has no useful ordinary derivative at most cost vectors. A differentiable alternative converts costs into normalized weights and takes their disparity expectation:

pd=exp⁡(−Cd/T)∑jexp⁡(−Cj/T),d^=∑d=0dmax⁡d pd,T>0.p_d=\frac{\exp(-C_d/T)}{\sum_j\exp(-C_j/T)},\qquad \widehat d=\sum_{d=0}^{d_{\max}}d\,p_d,\qquad T>0.

Lower costs get more weight. Subtracting the minimum cost before exponentiation improves numerical stability without changing the result. These normalized weights are not automatically calibrated probabilities of the physical correspondence. A common additive cost shift has no effect; multiplying costs and temperature by the same positive factor also preserves the weights. Soft argmin and cost scale

For cost C_j, the derivative is:

∂d^∂Cj=−pjT(j−d^).\frac{\partial\widehat d}{\partial C_j}=-\frac{p_j}{T}(j-\widehat d).

A finite-difference test checks every component. Rows whose costs are all infinite return an invalid result and zero weights/derivatives, rather than a fabricated disparity. A finite soft expectation lies within the candidate range, so targets outside that range cannot be fit by this operator.

Consider costs [0,10,0] at T=0.2. The endpoint weights are each approximately 0.5, the middle weight is about 9.64×10^-23, and the expectation is 1. The reported value falls at a candidate with almost no weight. Decreasing temperature cannot resolve two exactly equal separated modes. GC-Net explicitly discusses this multimodal issue; differentiability alone is not a guarantee of a plausible correspondence. Expectation under multiple modes

Our small learned example uses a shared 3×2 matrix W to map each RGB pixel into two features. It builds squared feature differences and minimizes masked disparity MSE:

fL=ILW,fR=IRW,C(y,x,d)=∥fL(y,x)−fR(y,x−d)∥22,L=1∣M∣∑(y,x)∈M(d^(y,x)−d∗(y,x))2.f_L=I_LW,\quad f_R=I_RW,\quad C(y,x,d)=\|f_L(y,x)-f_R(y,x-d)\|_2^2,\qquad L=\frac{1}{|M|}\sum_{(y,x)\in M}(\widehat d(y,x)-d^*(y,x))^2.

There are six learned weights. The gradient chain goes from MSE to disparity, from disparity through soft argmin to costs, and from squared differences to both feature maps and their shared weights. Contributions from multiple candidate shifts accumulate into the same right pixel. We check all six weight derivatives and all 60 input scalars across the two images.

This is a complete small learned-cost model, not a complete GC-Net. The original uses shared convolutional features, a concatenated cost volume, 3D contextual regularization and an L1 training loss. Our matrix features, squared differences and MSE make every derivative inspectable, while omitting that contextual network. Architecture and training loss

Run a stereo system that keeps its mistakes visible

Save this as stereo.py. It needs Python and NumPy; the checked environment is Python 3.12.4 with NumPy 1.26.4. It includes general two-camera geometry, a nonlearned matching pipeline and a separate differentiable feature-cost example. No external images, trained weights or GPU are needed.

"""Original calibrated stereo, matching and small learned-cost computations."""
import json
import numpy as np


def finite(value,shape=None):
    a=np.asarray(value,dtype=float)
    if not np.isfinite(a).all() or (shape is not None and a.shape!=shape):raise ValueError('Finite data with the stated shape required')
    return a


def fundamental(k_left,k_right,rotation,translation):
    kl,kr=finite(k_left,(3,3)),finite(k_right,(3,3));r=finite(rotation,(3,3));t=finite(translation,(3,))
    if np.linalg.norm(t)==0 or not np.allclose(r.T@r,np.eye(3)) or not np.isclose(np.linalg.det(r),1):raise ValueError('Nonzero baseline and proper rotation required')
    x,y,z=t;skew=np.array([[0,-z,y],[z,0,-x],[-y,x,0]])
    f=np.linalg.solve(kr.T,skew@r)@np.linalg.inv(kl)
    return f/np.linalg.norm(f)


def triangulate(left,right,p_left,p_right):
    l,r=finite(left,(2,)),finite(right,(2,));pl,pr=finite(p_left,(3,4)),finite(p_right,(3,4))
    a=np.array([l[0]*pl[2]-pl[0],l[1]*pl[2]-pl[1],r[0]*pr[2]-pr[0],r[1]*pr[2]-pr[1]])
    _,s,v=np.linalg.svd(a)
    if s[-2]<=1e-12*max(1.,s[0]) or abs(v[-1,3])<1e-12:raise ValueError('Degenerate or infinite triangulation')
    point=v[-1]/v[-1,3]
    if (pl@point)[2]<=0 or (pr@point)[2]<=0:raise ValueError('Triangulation behind a camera')
    return point[:3]


def disparity_depth(disparity,focal,baseline,principal_offset=0.,sigma_disparity=1.):
    d=np.asarray(disparity,dtype=float)
    if not np.isfinite([focal,baseline,principal_offset,sigma_disparity]).all() or focal<=0 or baseline<=0 or sigma_disparity<0:
        raise ValueError('Positive calibration and nonnegative disparity uncertainty required')
    corrected=d-principal_offset;valid=np.isfinite(corrected)&(corrected>0)
    z=np.full(d.shape,np.nan);sigma=np.full(d.shape,np.nan)
    z[valid]=focal*baseline/corrected[valid]
    sigma[valid]=focal*baseline*sigma_disparity/(corrected[valid]**2)
    return z,sigma,valid


def cost_volume(base,other,max_disparity,radius=0,direction=-1):
    """SSD patch mean. Other coordinate = base x + direction*d; d is nonnegative."""
    a=finite(base);b=finite(other,a.shape)
    if a.ndim not in [2,3] or not min(a.shape) or type(max_disparity) is not int or max_disparity<0 or type(radius) is not int or radius<0 or direction not in [-1,1]:
        raise ValueError('Invalid stereo image or search parameters')
    h,w=a.shape[:2];c=np.full((h,w,max_disparity+1),np.inf)
    for y in range(radius,h-radius):
        for x in range(radius,w-radius):
            for d in range(max_disparity+1):
                xr=x+direction*d
                if radius<=xr<w-radius:
                    left=a[y-radius:y+radius+1,x-radius:x+radius+1]
                    right=b[y-radius:y+radius+1,xr-radius:xr+radius+1]
                    c[y,x,d]=np.mean((left-right)**2)
    return c


DIRECTIONS=((0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1))


def path_costs(cost,direction,p1,p2):
    """Normalized SGM recurrence along one direction, with explicit invalid states."""
    c=np.asarray(cost,dtype=float)
    if c.ndim!=3 or not min(c.shape) or np.isnan(c).any() or np.isneginf(c).any() or np.any(c<0):raise ValueError('Nonnegative HWD costs, optionally positive infinity, required')
    if direction not in DIRECTIONS or not np.isfinite([p1,p2]).all() or not 0<=p1<=p2:raise ValueError('Invalid direction or penalties')
    h,w,d=c.shape;dy,dx=direction;l=np.full_like(c,np.inf)
    rows=range(h) if dy>=0 else range(h-1,-1,-1)
    cols=range(w) if dx>=0 else range(w-1,-1,-1)
    for y in rows:
        for x in cols:
            py,px=y-dy,x-dx
            if not (0<=py<h and 0<=px<w) or not np.isfinite(l[py,px]).any():
                l[y,x]=c[y,x];continue
            previous=l[py,px];minimum=previous.min()
            lower=np.r_[np.inf,previous[:-1]+p1];upper=np.r_[previous[1:]+p1,np.inf]
            transition=np.minimum.reduce([previous,lower,upper,np.full(d,minimum+p2)])
            l[y,x]=c[y,x]+transition-minimum
    return l


def sgm(cost,p1=.02,p2=.1,directions=DIRECTIONS):
    if not directions or len(set(directions))!=len(directions):raise ValueError('Nonempty unique directions required')
    total=np.zeros_like(np.asarray(cost,dtype=float))
    for direction in directions:total+=path_costs(cost,direction,p1,p2)
    valid=np.isfinite(total).any(axis=-1)
    disparity=total.argmin(axis=-1).astype(float);disparity[~valid]=np.nan
    return disparity,total


def left_right_check(left,right,tolerance=0.):
    """Integer disparity consistency; both maps store nonnegative magnitudes."""
    l=np.asarray(left,dtype=float);r=np.asarray(right,dtype=float)
    if l.ndim!=2 or l.shape!=r.shape or not min(l.shape) or not np.isfinite(tolerance) or tolerance<0:raise ValueError('Matching disparity maps required')
    for v in [l,r]:
        ok=np.isfinite(v)
        if np.any(v[ok]<0) or np.any(v[ok]!=np.floor(v[ok])):raise ValueError('Integer nonnegative disparities required')
    yy,xx=np.indices(l.shape);safe=np.where(np.isfinite(l),l,0)
    xr=xx-safe;inside=(xr>=0)&(xr<l.shape[1])
    ix=np.clip(xr,0,l.shape[1]-1).astype(int)
    matched=r[yy,ix]
    return np.isfinite(l)&inside&np.isfinite(matched)&(np.abs(l-matched)<=tolerance)


def soft_argmin(cost,temperature=1.):
    c=np.asarray(cost,dtype=float)
    if c.ndim<1 or not c.shape[-1] or np.isnan(c).any() or np.isneginf(c).any() or not np.isfinite(temperature) or temperature<=0:raise ValueError('Valid costs and positive temperature required')
    valid=np.isfinite(c).any(axis=-1)
    minimum=np.min(c,axis=-1,keepdims=True);minimum=np.where(np.isfinite(minimum),minimum,0)
    weight=np.exp(-(c-minimum)/temperature);total=weight.sum(axis=-1,keepdims=True)
    prob=np.divide(weight,total,out=np.zeros_like(weight),where=total>0)
    mean=np.sum(prob*np.arange(c.shape[-1]),axis=-1)
    derivative=-prob*(np.arange(c.shape[-1])-mean[...,None])/temperature
    mean=np.where(valid,mean,np.nan)
    return mean,prob,derivative,valid


def learned_cost_loss(left,right,weights,truth,mask,temperature=.5,max_disparity=2):
    """Six-parameter shared RGB-to-two-feature model, with full pixel/weight gradients.

    No 3D cost regularizer, CNN feature tower or full GC-Net is claimed.
    """
    a=finite(left);b=finite(right,a.shape);w=finite(weights,(3,2))
    if a.ndim!=3 or a.shape[2]!=3 or type(max_disparity) is not int or max_disparity<0:raise ValueError('RGB pair and nonnegative integer disparity limit required')
    y=finite(truth,a.shape[:2]);mask=np.asarray(mask,dtype=bool)
    if mask.shape!=y.shape or not mask.any():raise ValueError('Nonempty training mask required')
    fl,fr=a@w,b@w;h,width=y.shape;c=np.full((h,width,max_disparity+1),np.inf)
    for d in range(min(max_disparity,width-1)+1):c[:,d:,d]=np.sum((fl[:,d:]-fr[:,:width-d])**2,axis=-1)
    predicted,_,dc,_=soft_argmin(c,temperature)
    error=predicted-y;dp=np.zeros_like(error);dp[mask]=2*error[mask]/mask.sum()
    gc=dc*dp[:,:,None];gl=np.zeros_like(fl);gr=np.zeros_like(fr)
    for d in range(min(max_disparity,width-1)+1):
        delta=2*gc[:,d:,d,None]*(fl[:,d:]-fr[:,:width-d])
        gl[:,d:]+=delta;gr[:,:width-d]-=delta
    dw=np.einsum('hwi,hwj->ij',a,gl)+np.einsum('hwi,hwj->ij',b,gr)
    return float(np.mean(error[mask]**2)),dw,gl@w.T,gr@w.T,predicted


def render_scene(height=6,width=18):
    """Integer forward projection with a disparity z-buffer, not a real dataset."""
    rng=np.random.default_rng(21);left=rng.uniform(0,1,(height,width));right=rng.uniform(0,1,(height,width))
    truth=np.full((height,width),2,dtype=int);truth[:,8:12]=4
    owners=np.full((height,width),-1,dtype=int);closest=np.full((height,width),-1,dtype=int)
    for y,x in np.ndindex(truth.shape):
        xr=x-truth[y,x]
        if 0<=xr<width and truth[y,x]>closest[y,xr]:
            right[y,xr]=left[y,x];owners[y,xr]=x;closest[y,xr]=truth[y,x]
    visible=np.zeros_like(truth,dtype=bool)
    for y,xr in np.ndindex(owners.shape):
        if owners[y,xr]>=0:visible[y,owners[y,xr]]=True
    return left,right,truth,visible


def demo():
    focal,baseline=800.,.1;k=np.array([[focal,0,320],[0,focal,240],[0,0,1.]])
    pl=k@np.c_[np.eye(3),np.zeros(3)];pr=k@np.c_[np.eye(3),[-baseline,0,0]]
    point=np.array([.2,.1,4.,1.]);ql=pl@point;qr=pr@point;left_uv=ql[:2]/ql[2];right_uv=qr[:2]/qr[2]
    f=fundamental(k,k,np.eye(3),[-baseline,0,0])
    depth,sigma,_=disparity_depth([20,5],focal,baseline)
    a,b,truth,visible=render_scene();dl,_=sgm(cost_volume(a,b,5));dr,_=sgm(cost_volume(b,a,5,direction=1));valid=left_right_check(dl,dr)
    ambiguous=np.array([0.,10.,0.]);mean,prob,gradient,_=soft_argmin(ambiguous,.2)
    rgb=np.random.default_rng(37).normal(size=(2,5,3));other=np.roll(rgb,-1,axis=1);other[:,-1]=0
    weights=np.random.default_rng(12).normal(0,.3,(3,2));target=np.ones((2,5));mask=np.ones((2,5),dtype=bool);mask[:,0]=False
    loss,dw,_,_,_=learned_cost_loss(rgb,other,weights,target,mask);after=learned_cost_loss(rgb,other,weights-.1*dw,target,mask)[0]
    return {'projected_disparity':float(left_uv[0]-right_uv[0]),'triangulated_point':triangulate(left_uv,right_uv,pl,pr).tolist(),
            'epipolar_residual':float(np.r_[right_uv,1]@f@np.r_[left_uv,1]),'depths_for_disparities_20_5':depth.tolist(),'sigma_depth_for_one_pixel':sigma.tolist(),
            'principal_offset_example_depth':disparity_depth([40],focal,baseline,principal_offset=20)[0].tolist(),
            'visible_pixels':int(visible.sum()),'sgm_visible_mae':float(np.mean(np.abs(dl[visible]-truth[visible]))),
            'consistency_retained':int(valid.sum()),'consistent_visible_pixels':int((valid&visible).sum()),
            'consistent_but_occluded':int((valid&~visible).sum()),
            'soft_bimodal_mean':float(mean),'soft_bimodal_probabilities':prob.tolist(),'soft_bimodal_cost_derivative':gradient.tolist(),
            'learned_feature_parameters':weights.size,'learned_loss_before':loss,'learned_loss_after':after,
            'example_truth_row':truth[2].tolist(),'example_prediction_row':dl[2].tolist(),'example_visible_row':visible[2].tolist(),'example_consistency_row':valid[2].tolist()}


if __name__=='__main__':print(json.dumps(demo(),indent=2))

The actual output is:

{
  "projected_disparity": 20.0,
  "triangulated_point": [
    0.20000000000000032,
    0.09999999999999988,
    4.000000000000009
  ],
  "epipolar_residual": 0.0,
  "depths_for_disparities_20_5": [
    4.0,
    16.0
  ],
  "sigma_depth_for_one_pixel": [
    0.2,
    3.2
  ],
  "principal_offset_example_depth": [
    4.0
  ],
  "visible_pixels": 84,
  "sgm_visible_mae": 0.023809523809523808,
  "consistency_retained": 83,
  "consistent_visible_pixels": 81,
  "consistent_but_occluded": 2,
  "soft_bimodal_mean": 1.0,
  "soft_bimodal_probabilities": [
    0.5,
    9.643749239819589e-23,
    0.5
  ],
  "soft_bimodal_cost_derivative": [
    2.5,
    -0.0,
    -2.5
  ],
  "learned_feature_parameters": 6,
  "learned_loss_before": 0.010212785478271744,
  "learned_loss_after": 0.009377630401554395,
  "example_truth_row": [
    2,
    2,
    2,
    2,
    2,
    2,
    2,
    2,
    4,
    4,
    4,
    4,
    2,
    2,
    2,
    2,
    2,
    2
  ],
  "example_prediction_row": [
    0.0,
    0.0,
    2.0,
    2.0,
    2.0,
    2.0,
    0.0,
    3.0,
    4.0,
    4.0,
    4.0,
    4.0,
    2.0,
    2.0,
    2.0,
    2.0,
    2.0,
    2.0
  ],
  "example_visible_row": [
    false,
    false,
    true,
    true,
    true,
    true,
    false,
    false,
    true,
    true,
    true,
    true,
    true,
    true,
    true,
    true,
    true,
    true
  ],
  "example_consistency_row": [
    false,
    false,
    true,
    true,
    true,
    true,
    false,
    true,
    false,
    true,
    true,
    true,
    true,
    true,
    true,
    true,
    true,
    true
  ]
}

The 6×18 synthetic scene contains background disparity 2 and a nearer foreground strip at disparity 4. Integer forward projection uses a disparity z-buffer: the nearer point wins when two left pixels project to the same right pixel. Out-of-view and hidden left pixels are excluded from the visible mask; right pixels with no projected owner retain independently generated values.

There are 84 visible pixels. SGM’s visible-pixel disparity MAE is about 0.02381. Left-right checking retains 83 pixels, of which 81 are visible and 2 are occluded. Those two are false acceptances. A metric computed only on retained pixels must also report coverage and distinguish true visibility from a method’s predicted validity.

The learned example reduces MSE from approximately 0.0102128 to 0.00937763 after one update. It is a synthetic derivative check, not a stereo benchmark. The geometry example reconstructs [0.2,0.1,4] up to floating-point precision and gives an epipolar residual of zero for the constructed pair.

For H×W images, D candidates, c channels and a k×k patch, the direct SSD implementation costs order HWDk²c operations. Each of R SGM directions costs order HWD, using a shared predecessor minimum rather than enumerating all D² transitions. The implementation retains the cost volume, aggregate and one path volume, so its main memory is order HWD. Left-right checking is linear in HW; soft argmin and the learned candidate costs are linear in HWD for fixed feature width. These are operation counts for this implementation, not hardware latency predictions.

The tests compare every pixel of each of the eight path directions on a small grid with exhaustive path-label enumeration. They also check nonrectified geometry, degenerate triangulation, disparity/offset scaling, uncertainty derivatives, scalar patch costs, invalid states, the 2D energy counterexample, reverse-map signs, soft-argmin gradients, full learned gradients and actual updates.

A stereo score needs its geometry and its missing pixels

  • No correspondence exists behind an occluder. Smoothness may fill a plausible value, but it has supplied a prior rather than a direct measurement. Return or evaluate invalid regions explicitly.
  • Repeated and weak texture remain ambiguous. Larger windows or stronger penalties add context while risking mixed-depth support and oversmoothing. Subpixel output is not automatically subpixel accuracy.
  • Calibration matters. Wrong focal length, baseline units, principal points, lens correction or rectification can corrupt an otherwise correct match. The simple uncertainty formula excludes calibration error.
  • Photometric and timing assumptions matter. Exposure differences, reflection, transparency and scene motion between captures can invalidate the patch comparison. Learned features require their own robustness checks.
  • This implementation has a finite integer search range. It is not an arbitrary-orientation dense matcher, a full SGM reference implementation, a subpixel reverse-map validator or a trained foundation model.

An evaluation should state the dataset split, image resolution, disparity/depth units, valid and occlusion masks, search range, error thresholds and retained-pixel coverage. Compare a nonlearned baseline under the same conditions. Runtime claims need the device, image size, precision and complete processing pipeline; they cannot be inferred from the parameter count alone.

Four ways to challenge a correspondence

  1. Calibration: f=800 pixels, B=0.1 meters, raw disparity 40 pixels, and cxL−cxR=20 pixels. What depth do you recover? What happens if you ignore the principal-point offset?

Answer: Corrected disparity is 20, giving 800×0.1/20=4 meters. Ignoring the offset gives 2 meters. If all pixel coordinates are rescaled by one half, f, raw disparity and the principal-point offset must all halve; the correct depth remains 4 meters.

  1. Ambiguity: a cost vector is [0,10,0]. Why does soft argmin return 1? Will an arbitrarily small positive temperature necessarily select one endpoint?

Answer: The endpoint costs are equal, so their weights stay equal. The expectation is 1 by symmetry, even though the middle candidate is expensive. Smaller temperature suppresses the middle weight but does not break the endpoint tie. Inspect the distribution or return ambiguity; do not describe its mean as a supported mode.

  1. Consistency: left pixels x=1,d=1 and x=2,d=2 both map to right x=0, whose reverse disparity is1. With tolerance 1, which pass? Does the check prove unique matching?

Answer: Both pass: the disparity differences are 0 and 1. Both still use the same right pixel, so the tolerant check does not prove uniqueness. With tolerance 0 only the first passes in this example, but even an exact bidirectional match can be physically wrong in a repeated pattern.

  1. Experiment: SGM has low error on the visible mask, while its consistency check retains two occluded pixels. What should you report, and what does the 2D energy counterexample rule out?

Answer: Report visible-pixel error, true visibility, predicted-valid coverage and false acceptances separately. Here 83 pixels pass consistency, including 81 visible and 2 occluded. The energy 14 versus optimal 10 counterexample rules out a general exact-2D-optimum claim for the stated SGM aggregation and grid objective; it does not say SGM is never useful or that all datasets have this error.

From explicit matching costs to learned context

The inspected Scharstein–Szeliski report is dated November 2001; it is not the later journal version. Its decomposition remains useful for distinguishing what changed in a stereo system. Hirschmüller’s CVPR 2005 paper develops SGM and mutual-information matching. Our recurrence follows the inspected method, while our SSD cost and fixed-penalty simplifications remain explicit. 2001 technical report 2005 paper

GC-Net’s first arXiv submission was 2017-03-13. The inspected ICCV 2017 version learns feature representations and 3D context while regressing disparity with soft argmin. The change is broader than replacing a hand-designed pixel difference with one learned number: the cost volume and contextual regularization are part of the system. Paper First-submission record

FoundationStereo was first submitted on 2025-01-17. In the inspected CVPR 2025 method pages, a frozen Depth Anything V2 backbone contributes features through a side adapter, combined with a stereo feature pathway. The system builds a hybrid correlation/concatenation volume and filters it before recurrent refinement. This uses monocular features as contextual information; it is not simply treating an ambiguous monocular depth prediction as calibrated stereo ground truth. Inspected architecture First-submission record

The name “zero-shot” describes a training/evaluation relationship, not a guarantee for every scene. This article does not reproduce FoundationStereo’s full network, all training conditions or its reported benchmark results. For a follow-up project, hold calibration and evaluation masks fixed, compare SSD and SGM, then replace the cost with a learned model. Track where errors move: textureless regions, depth boundaries, occlusions or out-of-domain scenes. That makes the contribution of each change testable.

Make a prediction, then check

Costs at disparities 0, 1 and 2 are [0, 10, 0]. Why does soft argmin give 1?

Choose one answer

Learning objectives

  • Derive epipolar geometry, triangulation and depth with the principal-point offset.
  • Implement cost volumes and eight-direction SGM while distinguishing path optimality from a 2D optimum.
  • Differentiate a complete small learned stereo cost and expose multimodal soft-argmin failures.
  • Separate calibration, visibility, predicted validity and retained-pixel evaluation.

Prerequisites & connections

Explore related knowledge →

References

  1. OpenCV 4.12.0 — Camera Calibration and 3D Reconstruction
    OpenCV contributors
  2. A Taxonomy and Evaluation of Dense Two-Frame Stereo Correspondence Algorithms
    Daniel Scharstein; Richard Szeliski · 2001
  3. Accurate and Efficient Stereo Processing by Semi-Global Matching and Mutual Information
    Heiko Hirschmüller · 2005
  4. End-to-End Learning of Geometry and Context for Deep Stereo Regression
    Kendall, Alex; Martirosyan, Hayk; Dasgupta, Saumitro; Henry, Peter; Kennedy, Ryan; Bachrach, Abraham; Bry, Adam · 2017
  5. FoundationStereo: Zero-Shot Stereo Matching
    Wen, Bowen; Trepte, Matthew; Aribido, Joseph; Kautz, Jan; Gallo, Orazio; Birchfield, Stan · 2025
  6. End-to-End Learning of Geometry and Context for Deep Stereo Regression — submission history
    arXiv · 2017
  7. FoundationStereo: Zero-Shot Stereo Matching — submission history
    arXiv · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped original papers, official camera documentation and applicable pinned code; 26 numerical, bilingual and figure checks; 12 equations per language, complete program and actual output, four explained exercises, original computed figures with four-font boundary checks. Not human peer review, a full foundation model or a real-data benchmark.

  • 26 formal checks cover independent geometry/gradient/boundary calculations, bilingual/reference/exercise consistency and this topic’s computed figures. The two-topic total of 54 includes 42 numerical tests, not 54 independent numerical reproductions.
  • Twelve display equations match exactly across languages; the complete embedded program reproduces the displayed output, and four explained answers are checked. Reading scopes and source-equation ambiguities are explicit; unreconciled derivations are not adopted.
  • Four original SVGs across languages and desktop/mobile layouts were inspected with four-font boundary checks. Figures use outputs checked against the program; synthetic inputs, scale assistance and failure cases are not presented as benchmark performance.
  • Checked exhaustive eight-direction paths, 2D energy 14 versus 10, six parameter and 60 input gradients, principal-point disparity offset, two occlusion false acceptances and bimodal mean 1.
  • Final static inspection found visible strong-emphasis delimiters in Chinese list headings. Converted nine exact spans to strong tags; reversing those substitutions reproduces the original text exactly, with equations, code, references and wording unchanged. Original article/review records are archived and the six-file freeze is unchanged.
  • Added the epipole degeneracy Fp=0 and a bilingual coplanarity/triple-product derivation. Directly computed a nonrectified camera’s left epipole and verified every Fp component within 1e-12; equations, code, references and numerical examples are unchanged.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.