iris / backend /experimental /lightglue_matching.py
github-actions[bot]
Automated Deploy: f334c0ad60590803e1c813b87a0f019dd5fbaedd
1d21e88
Raw History Blame Contribute Delete
3.7 kB
"""Offline ALIKED + LightGlue adapter using the already pinned Kornia dependency."""
from pathlib import Path
import hashlib
import cv2
import numpy as np
from .preprocessing import iris_mask, glare_mask
class LightGlueMatcher:
def __init__(self, weights_dir, max_size=1600, device='cpu'):
import torch
from kornia.feature import ALIKED, LightGlue
if not 400 <= max_size <= 2200:
raise ValueError('ALIKED resolution must be between 400 and 2200.')
self.torch, self.device, self.max_size = torch, device, max_size
for name, checksum in [('aliked-n16.pth', '5be8704840ed662d9d8c561bf7279c222092674e7eb05fd0feab94899e9d82f2'), ('aliked_lightglue.pth', 'd975e965b105311a6143194852297dff4f02aea5cc2e10cecfed966ca0e22503')]:
if hashlib.sha256((Path(weights_dir)/name).read_bytes()).hexdigest() != checksum:
raise RuntimeError(f'{name} failed checkpoint integrity verification.')
torch.set_num_threads(4)
self.extractor = ALIKED(max_num_keypoints=4096).eval().to(device)
state = torch.load(Path(weights_dir)/'aliked-n16.pth', map_location='cpu', weights_only=True)
# Kornia owns this deterministic grid buffer; the original checkpoint omits it.
state['dkd.hw_grid'] = self.extractor.state_dict()['dkd.hw_grid']
self.extractor.load_state_dict(state, strict=True)
self.model = LightGlue(features=None, input_dim=128, depth_confidence=-1, width_confidence=-1).eval().to(device)
state = torch.load(Path(weights_dir)/'aliked_lightglue.pth', map_location='cpu', weights_only=True)
for i in range(9):
for old, new in ((f'self_attn.{i}', f'transformers.{i}.self_attn'), (f'cross_attn.{i}', f'transformers.{i}.cross_attn')):
state = {k.replace(old, new): v for k, v in state.items()}
state['confidence_thresholds'] = self.model.state_dict()['confidence_thresholds']
self.model.load_state_dict(state, strict=True)
def __call__(self, reference, moving, masks=None):
features, scales = [], []
for index, im in enumerate((reference, moving)):
h, w = im.shape[:2]
factor = min(1., self.max_size/max(h, w))
size = (max(32, int(w*factor)//32*32), max(32, int(h*factor)//32*32))
gray = cv2.cvtColor(cv2.resize(im, size), cv2.COLOR_BGR2GRAY)
gray = cv2.createCLAHE(2, (12, 12)).apply(gray)
tensor = self.torch.from_numpy(gray.copy()).float()[None, None].to(self.device)/255
scale = np.float32([w/size[0], h/size[1]])
with self.torch.inference_mode():
f = self.extractor(tensor)[0]
points = f.keypoints.cpu().numpy()*scale
mask = (iris_mask(im) if masks is None else masks[index]) & ~glare_mask(im)
xy = np.rint(points).astype(int)
valid = (xy[:, 0]>=0)&(xy[:, 0]<w)&(xy[:, 1]>=0)&(xy[:, 1]<h)
valid[valid] &= mask[xy[valid, 1], xy[valid, 0]]
keep = self.torch.from_numpy(valid).to(self.device)
features.append(dict(keypoints=f.keypoints[keep][None], descriptors=f.descriptors[keep][None], image_size=self.torch.tensor([size], device=self.device)))
scales.append(scale)
if any(f['keypoints'].shape[1] < 2 for f in features):
return np.empty((0, 2), np.float32), np.empty((0, 2), np.float32)
with self.torch.inference_mode():
result = self.model(dict(image0=features[0], image1=features[1]))
pairs = result['matches'][0]
return tuple((features[i]['keypoints'][0, pairs[:, i]].cpu().numpy()*scales[i]).astype(np.float32) for i in range(2))