Spaces:
Paused
Paused
Download hf_workspace/backend/experimental/refinement.py from modventures/iris: direct link, hf CLI and curl.
- Browser
- Download file 2.29 kB
-
https://huggingface.co/spaces/modventures/iris/resolve/main/hf_workspace/backend/experimental/refinement.py
- Command line
-
hf download hf://spaces/modventures/iris/hf_workspace/backend/experimental/refinement.py
-
curl -L -o refinement.py https://huggingface.co/spaces/modventures/iris/resolve/main/hf_workspace/backend/experimental/refinement.py
2.29 kB
| """Iris-only local refinement with illumination-normalized correspondence copies.""" | |
| import cv2 | |
| import numpy as np | |
| from .preprocessing import iris_mask,glare_mask,normalize | |
| def local_map(reference,moving,homography): | |
| h,w=reference.shape[:2] | |
| factor=min(1,1200/max(h,w));size=(round(w*factor),round(h*factor)) | |
| global_image=cv2.warpPerspective(moving,homography,(w,h)) | |
| a=cv2.resize(reference,size);b=cv2.resize(global_image,size) | |
| na,nb=normalize(a),normalize(b) | |
| valid=iris_mask(a)&~glare_mask(a)&~glare_mask(b) | |
| def flow(x,y):return cv2.calcOpticalFlowFarneback(x,y,None,.5,5,35,6,7,1.5,0) | |
| f=cv2.GaussianBlur(flow(na,nb),(0,0),2) | |
| rev=flow(nb,na) | |
| yy,xx=np.indices(na.shape,dtype=np.float32) | |
| mx,my=xx+f[...,0],yy+f[...,1] | |
| fb=np.linalg.norm(f+cv2.remap(rev,mx,my,cv2.INTER_LINEAR),axis=2) | |
| uy,ux=np.gradient(f[...,0]);vy,vx=np.gradient(f[...,1]);jac=(1+ux)*(1+vy)-uy*vx | |
| strain=np.sqrt(ux**2+uy**2+vx**2+vy**2) | |
| aligned=cv2.remap(nb,mx,my,cv2.INTER_LINEAR) | |
| err0=cv2.GaussianBlur(cv2.absdiff(na,nb).astype(np.float32),(0,0),2) | |
| err1=cv2.GaussianBlur(cv2.absdiff(na,aligned).astype(np.float32),(0,0),2) | |
| sampling_valid=cv2.remap(valid.astype(np.uint8),mx,my,cv2.INTER_NEAREST)>0 | |
| trust=valid&sampling_valid&(fb<1)&(np.linalg.norm(f,axis=2)<18)&(jac>.65)&(jac<1.5)&(strain<.45)&(err1<18)&(err1<=err0+1) | |
| trust=cv2.erode(trust.astype(np.uint8),np.ones((5,5),np.uint8)).astype(bool) | |
| fraction=float(trust.sum()/max(valid.sum(),1)) | |
| improvement=float(1-err1[trust].mean()/max(err0[trust].mean(),.01)) if trust.any() else 0 | |
| # The same support and improvement gates as the original local stage. | |
| apply=fraction>.45 and improvement>.15 | |
| full=cv2.resize(f,(w,h))/factor if apply else np.zeros((h,w,2),np.float32) | |
| trusted=cv2.resize(trust.astype(np.uint8),(w,h),interpolation=cv2.INTER_NEAREST).astype(bool) | |
| y,x=np.indices((h,w),dtype=np.float32);x+=full[...,0];y+=full[...,1] | |
| inv=np.linalg.inv(homography);den=inv[2,0]*x+inv[2,1]*y+inv[2,2] | |
| mapx=((inv[0,0]*x+inv[0,1]*y+inv[0,2])/den).astype(np.float32) | |
| mapy=((inv[1,0]*x+inv[1,1]*y+inv[1,2])/den).astype(np.float32) | |
| return np.stack([mapx,mapy],-1),trusted,dict(applied=apply,trusted_iris_fraction=fraction,improvement=improvement),global_image | |