-
Notifications
You must be signed in to change notification settings - Fork 105
/
homography_est.py
74 lines (63 loc) · 2.41 KB
/
homography_est.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import numpy as np
import torch
from homography_est import (
LineSegment,
ransac_line_homography,
ransac_point_homography,
ransac_point_line_homography,
)
from ...utils.tensor import batch_to_numpy
from ..base_estimator import BaseEstimator
def H_estimation_hybrid(kpts0=None, kpts1=None, lines0=None, lines1=None, tol_px=5):
"""Estimate a homography from points and lines with hybrid RANSAC.
All features are expected in x-y convention
"""
# Check that we have at least 4 features
n_features = 0
if kpts0 is not None:
n_features += len(kpts0) + len(kpts1)
if lines0 is not None:
n_features += len(lines0) + len(lines1)
if n_features < 4:
return None
if lines0 is None:
# Point-only RANSAC
H = ransac_point_homography(kpts0, kpts1, tol_px, False, [])
elif kpts0 is None:
# Line-only RANSAC
ls0 = [LineSegment(line[0], line[1]) for line in lines0]
ls1 = [LineSegment(line[0], line[1]) for line in lines1]
H = ransac_line_homography(ls0, ls1, tol_px, False, [])
else:
# Point-lines RANSAC
ls0 = [LineSegment(line[0], line[1]) for line in lines0]
ls1 = [LineSegment(line[0], line[1]) for line in lines1]
H = ransac_point_line_homography(kpts0, kpts1, ls0, ls1, tol_px, False, [], [])
if np.abs(H[-1, -1]) > 1e-8:
H /= H[-1, -1]
return H
class PointLineHomographyEstimator(BaseEstimator):
default_conf = {"ransac_th": 2.0, "options": {}}
required_data_keys = ["m_kpts0", "m_kpts1", "m_lines0", "m_lines1"]
def _init(self, conf):
pass
def _forward(self, data):
feat = data["m_kpts0"] if "m_kpts0" in data else data["m_lines0"]
data = batch_to_numpy(data)
m_features = {
"kpts0": data["m_kpts1"] if "m_kpts1" in data else None,
"kpts1": data["m_kpts0"] if "m_kpts0" in data else None,
"lines0": data["m_lines1"] if "m_lines1" in data else None,
"lines1": data["m_lines0"] if "m_lines0" in data else None,
}
M = H_estimation_hybrid(**m_features, tol_px=self.conf.ransac_th)
success = M is not None
if not success:
M = torch.eye(3, device=feat.device, dtype=feat.dtype)
else:
M = torch.from_numpy(M).to(feat)
estimation = {
"success": success,
"M_0to1": M,
}
return estimation