File size: 2,806 Bytes
b5af7d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d21e88
b5af7d6
 
 
1d21e88
 
b5af7d6
 
 
 
 
1d21e88
b5af7d6
 
1d21e88
b5af7d6
 
 
 
 
 
 
 
1d21e88
 
b5af7d6
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""Classical and learned correspondence adapters with explicit offline weights."""
from pathlib import Path
import cv2
import numpy as np
from .preprocessing import iris_mask,glare_mask


def sift_matches(reference,moving):
    points=[];descriptors=[]
    for im in (reference,moving):
        factor=1400/max(im.shape[:2]);size=(round(im.shape[1]*factor),round(im.shape[0]*factor))
        small=cv2.resize(im,size)
        g=cv2.cvtColor(small,cv2.COLOR_BGR2GRAY)
        g=cv2.createCLAHE(clipLimit=2,tileGridSize=(12,12)).apply(g)
        mask=(iris_mask(small)&~glare_mask(small)).astype(np.uint8)*255
        kp,des=cv2.SIFT_create(nfeatures=7000,contrastThreshold=.015).detectAndCompute(g,mask)
        points.append(np.float32([k.pt for k in kp])/factor);descriptors.append(des)
    if any(d is None for d in descriptors):return np.empty((0,2),np.float32),np.empty((0,2),np.float32)
    pairs=cv2.BFMatcher().knnMatch(descriptors[0],descriptors[1],k=2)
    good=[p[0] for p in pairs if len(p)==2 and p[0].distance<.72*p[1].distance]
    return points[0][[m.queryIdx for m in good]],points[1][[m.trainIdx for m in good]]


class LearnedMatcher:
    def __init__(self,weights,device='cpu',max_size=800):
        import torch
        from kornia.feature import LoFTR
        self.torch=torch;self.device=device
        if not 400 <= max_size <= 1200:raise ValueError('LoFTR resolution must be between 400 and 1200.')
        self.max_size=max_size
        torch.set_num_threads(4)
        self.model=LoFTR(pretrained=None).eval().to(device)
        state=torch.load(Path(weights),map_location='cpu',weights_only=True)
        self.model.load_state_dict(state['state_dict'])

    def __call__(self,reference,moving,masks=None):
        tensors=[];scales=[]
        for im in (reference,moving):
            h,w=im.shape[:2];factor=min(1,self.max_size/max(h,w));size=(max(8,int(w*factor)//8*8),max(8,int(h*factor)//8*8))
            g=cv2.cvtColor(cv2.resize(im,size),cv2.COLOR_BGR2GRAY)
            g=cv2.createCLAHE(clipLimit=2,tileGridSize=(12,12)).apply(g)
            tensors.append(self.torch.from_numpy(g.copy()).float()[None,None].to(self.device)/255)
            scales.append(np.array([w/size[0],h/size[1]],np.float32))
        with self.torch.inference_mode():
            out=self.model({'image0':tensors[0],'image1':tensors[1]})
        a=out['keypoints0'].cpu().numpy()*scales[0];b=out['keypoints1'].cpu().numpy()*scales[1]
        keep=out['confidence'].cpu().numpy()>.7
        for index,(im,p) in enumerate([(reference,a),(moving,b)]):
            mask=(iris_mask(im) if masks is None else masks[index])&~glare_mask(im)
            x=np.clip(p[:,0].astype(int),0,im.shape[1]-1);y=np.clip(p[:,1].astype(int),0,im.shape[0]-1)
            keep &= mask[y,x]
        return a[keep],b[keep]