Spaces:
Paused
Paused
Download backend/experimental/mesh.py from modventures/iris: direct link, hf CLI and curl.
- Browser
- Download file 3.38 kB
-
https://huggingface.co/spaces/modventures/iris/resolve/main/backend/experimental/mesh.py
- Command line
-
hf download hf://spaces/modventures/iris/backend/experimental/mesh.py
-
curl -L -o mesh.py https://huggingface.co/spaces/modventures/iris/resolve/main/backend/experimental/mesh.py
3.38 kB
| """Regularized bilinear correspondence mesh with robust residual fitting. | |
| Fits training correspondences only. Callers must validate held-out matches and | |
| inspect image detail; estimated matches are not anatomical ground truth. | |
| """ | |
| import cv2 | |
| import numpy as np | |
| def basis(points,shape,side=9): | |
| h,w=shape | |
| q=points/np.float32([w-1,h-1])*(side-1) | |
| q=np.clip(q,0,side-1) | |
| ix=np.minimum(np.floor(q).astype(int),side-2);frac=q-ix | |
| a=np.zeros((len(points),side*side),np.float64) | |
| for dy,dx in [(0,0),(0,1),(1,0),(1,1)]: | |
| weight=(frac[:,0] if dx else 1-frac[:,0])*(frac[:,1] if dy else 1-frac[:,1]) | |
| a[np.arange(len(points)),(ix[:,1]+dy)*side+ix[:,0]+dx]=weight | |
| return a | |
| def fit_mesh(reference_points,moving_points,homography,shape,side=9): | |
| if len(reference_points)<24:raise ValueError('Too few mesh constraints') | |
| inverse=np.linalg.inv(homography) | |
| prediction=cv2.perspectiveTransform(reference_points[None],inverse)[0] | |
| residual=moving_points-prediction | |
| a=basis(reference_points,shape,side) | |
| # Penalize second differences, favoring smooth local motion over isolated bends. | |
| penalties=[] | |
| for y in range(side): | |
| for x in range(side): | |
| for dy,dx in [(0,1),(1,0)]: | |
| if y+2*dy<side and x+2*dx<side: | |
| row=np.zeros(side*side) | |
| for offset,value in [(0,1),(1,-2),(2,1)]:row[(y+offset*dy)*side+x+offset*dx]=value | |
| penalties.append(row) | |
| lap=np.array(penalties);regularizer=2*(lap.T@lap)+.03*np.eye(side*side) | |
| weight=np.ones(len(a)) | |
| for _ in range(6): | |
| coef=np.linalg.solve(a.T@(weight[:,None]*a)+regularizer,a.T@(weight[:,None]*residual)) | |
| err=np.linalg.norm(a@coef-residual,axis=1) | |
| weight=np.minimum(1,3/np.maximum(err,1e-6)) | |
| return coef.reshape(side,side,2).astype(np.float32) | |
| def interpolate_mesh(coefficients,shape): | |
| """Exact separable bilinear interpolation, consistent with point predictions. | |
| cv2.remap quantizes fractional grid coordinates to 1/32. On a sparse 9x9 | |
| deformation grid that creates displacement steps and spurious Jacobian spikes. | |
| """ | |
| h,w=shape;side=coefficients.shape[0] | |
| x=np.linspace(0,side-1,w,dtype=np.float32) | |
| y=np.linspace(0,side-1,h,dtype=np.float32) | |
| ix=np.minimum(x.astype(int),side-2);iy=np.minimum(y.astype(int),side-2) | |
| fx=(x-ix).astype(np.float32)[None,:,None] | |
| fy=(y-iy).astype(np.float32)[:,None,None] | |
| rows=coefficients[:,ix]*(1-fx)+coefficients[:,ix+1]*fx | |
| return rows[iy]*(1-fy)+rows[iy+1]*fy | |
| def dense_mesh(coefficients,homography,shape): | |
| h,w=shape;side=coefficients.shape[0] | |
| y,x=np.indices((h,w),dtype=np.float32) | |
| delta=interpolate_mesh(coefficients,shape) | |
| inv=np.linalg.inv(homography);den=inv[2,0]*x+inv[2,1]*y+inv[2,2] | |
| mx=((inv[0,0]*x+inv[0,1]*y+inv[0,2])/den).astype(np.float32)+delta[...,0] | |
| my=((inv[1,0]*x+inv[1,1]*y+inv[1,2])/den).astype(np.float32)+delta[...,1] | |
| uy,ux=np.gradient(delta[...,0]);vy,vx=np.gradient(delta[...,1]) | |
| jac=(1+ux)*(1+vy)-uy*vx | |
| strain=np.sqrt(ux**2+uy**2+vx**2+vy**2) | |
| mapxy,mapxx=np.gradient(mx);mapyy,mapyx=np.gradient(my) | |
| full_jac=mapxx*mapyy-mapxy*mapyx | |
| good=(full_jac>0)&np.isfinite(full_jac)&(mx>=0)&(mx<w)&(my>=0)&(my<h)&(np.linalg.norm(delta,axis=2)<35)&(jac>.65)&(jac<1.5)&(strain<.45) | |
| return np.stack([mx,my],-1),good,delta | |