image.process\feature\match.mbt
87.1% · 74 / 85 points · 300 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 模板匹配 match - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// SIFT 描述子匹配 + RANSAC 单应性估计(纯 MoonBit) - 7
- 8
///| - 9
/// SIFT 匹配结果 - 10
pub(all) struct SiftMatch { - 11
query_idx : Int32 - 12
train_idx : Int32 - 13
distance : Float // L2 距离 - 14
} - 15
- 16
///| - 17
/// SIFT 描述子匹配。 - 18
/// 使用 L2 距离(欧氏距离)匹配 SIFT 描述子。 - 19
/// max_distance 为最大允许距离,ratio_test 为 Lowe 比率测试阈值。 - 20
pub fn sift_match( - 21
query : Array[SiftDescriptor], - 22
train : Array[SiftDescriptor], - 23
max_distance~ : Float = 300.0F, - 24
ratio_test~ : Float = 0.75F, - 25
) -> Array[SiftMatch] raise @types.LoadError { - 26
// 参数验证 - 27●
if max_distance <= 0.0F { - 28○
raise @types.LoadError::DecodeFailed( - 29
"sift_match: max_distance必须大于0", - 30
) - 31
} - 32
if ratio_test <= 0.0F || ratio_test >= 1.0F { - 33○
raise @types.LoadError::DecodeFailed( - 34
"sift_match: ratio_test必须在0-1之间", - 35
) - 36
} - 37
// 空数组直接返回空结果 - 38●
if query.length() == 0 || train.length() == 0 { - 39●
return [] - 40
} - 41
- 42
let matches : Array[SiftMatch] = [] - 43●
for qi in 0..<query.length() { - 44●
let qd = query[qi].data - 45
// 找最近和次近 - 46
let mut best1_dist = 10000000000.0F - 47
let mut best1_idx = -1 - 48
let mut best2_dist = 10000000000.0F - 49●
for ti in 0..<train.length() { - 50●
let td = train[ti].data - 51●
let d = l2_distance(qd, td) - 52
if d < best1_dist { - 53●
best2_dist = best1_dist - 54
best1_dist = d - 55
best1_idx = ti - 56●
} else if d < best2_dist { - 57●
best2_dist = d - 58
} - 59
} - 60
if best1_idx >= 0 && best1_dist < max_distance { - 61
// Lowe 比率测试 - 62●
if best2_dist > 0.0F && best1_dist / best2_dist < ratio_test { - 63●
matches.push(SiftMatch::{ - 64
query_idx: qi, - 65
train_idx: best1_idx, - 66
distance: best1_dist, - 67
}) - 68
} - 69
} - 70
} - 71
matches - 72
} - 73
- 74
///| - 75
/// RANSAC 单应性矩阵估计。 - 76
/// 从匹配点对估计 3x3 单应性矩阵(h33=1,返回 8 个值)。 - 77
/// iterations 为 RANSAC 迭代次数,threshold 为重投影误差阈值。 - 78
pub fn ransac_homography( - 79
matches : Array[((Float, Float), (Float, Float))], - 80
iterations~ : Int32 = 1000, - 81
threshold~ : Float = 3.0F, - 82
) -> Array[Float]? raise @types.LoadError { - 83
// 参数验证 - 84●
if iterations <= 0 { - 85○
raise @types.LoadError::DecodeFailed( - 86
"ransac_homography: iterations必须大于0", - 87
) - 88
} - 89
if threshold <= 0.0F { - 90○
raise @types.LoadError::DecodeFailed( - 91
"ransac_homography: threshold必须大于0", - 92
) - 93
} - 94
- 95●
let n = matches.length() - 96
if n < 4 { - 97●
return None - 98
} - 99
let mut best_h : Array[Float]? = None - 100
let mut best_inliers = 0 - 101
for iter in 0..<iterations { - 102
// 确定性选 4 对点(基于迭代号散列) - 103●
let indices = deterministic_indices(n, 4, iter) - 104
let pts : Array[((Float, Float), (Float, Float))] = [] - 105
for idx in indices { - 106●
pts.push(matches[idx]) - 107
} - 108
// 计算单应性矩阵 - 109●
let h = compute_homography_dlt(pts) - 110●
if h.is_empty() { - 111○
continue - 112
} - 113
// 统计内点 - 114
let mut inliers = 0 - 115
for i in 0..<n { - 116●
let ((qx, qy), (tx, ty)) = matches[i] - 117●
let err = reprojection_error(h, qx, qy, tx, ty) - 118
if err < threshold { - 119●
inliers += 1 - 120
} - 121
} - 122
if inliers > best_inliers { - 123●
best_inliers = inliers - 124
best_h = Some(h) - 125
} - 126
} - 127
best_h - 128
} - 129
- 130
// ==================== 内部实现 ==================== - 131
- 132
///| - 133
fn l2_distance(a : Array[Float], b : Array[Float]) -> Float { - 134◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 135
let mut sum = 0.0F - 136
for i in 0..<n { - 137●
let d = a[i] - b[i] - 138
sum += d * d - 139
} - 140●
sum.sqrt() - 141
} - 142
- 143
///| - 144
fn deterministic_indices(n : Int32, k : Int32, seed : Int32) -> Array[Int32] { - 145●
let result : Array[Int32] = [] - 146
let mut s = seed - 147
let mut count = 0 - 148
let mut attempts = 0 - 149
let max_attempts = n * 4 - 150
while count < k && count < n && attempts < max_attempts { - 151●
attempts += 1 - 152
s = (s * 31 + 17) % n - 153
if s < 0 { - 154○
s = -s - 155
} - 156
let idx = s % n - 157
let mut dup = false - 158
for r in result { - 159●
if r == idx { - 160●
dup = true - 161
break - 162
} - 163
} - 164
if !dup { - 165●
result.push(idx) - 166
count += 1 - 167
} - 168
s += 1 - 169
} - 170
// 如果不够,补充前面的 - 171
for i in 0..<n { - 172●
if result.length() >= k { - 173●
break - 174
} - 175
let mut dup = false - 176
for r in result { - 177●
if r == i { - 178●
dup = true - 179
break - 180
} - 181
} - 182
if !dup { - 183●
result.push(i) - 184
} - 185
} - 186
result - 187
} - 188
- 189
///| - 190
fn compute_homography_dlt( - 191
pts : Array[((Float, Float), (Float, Float))], - 192
) -> Array[Float] { - 193●
if pts.length() < 4 { - 194○
return [] - 195
} - 196
// 构建 8x8 线性方程组 A*h = b - 197
// h = [h11, h12, h13, h21, h22, h23, h31, h32] - 198
// 对于每对点 (x,y) -> (u,v): - 199
// u = (h11*x + h12*y + h13) / (h31*x + h32*y + 1) - 200
// v = (h21*x + h22*y + h23) / (h31*x + h32*y + 1) - 201
// 线性化: - 202
// x*h11 + y*h12 + h13 - x*u*h31 - y*u*h32 = u - 203
// x*h21 + y*h22 + h23 - x*v*h31 - y*v*h32 = v - 204
let a : Array[Array[Float]] = [] - 205
let b : Array[Float] = [] - 206
for i in 0..<4 { - 207●
let ((x, y), (u, v)) = pts[i] - 208
// 第一行 - 209●
let row1 : Array[Float] = Array::make(8, 0.0F) - 210
row1[0] = x - 211
row1[1] = y - 212
row1[2] = 1.0F - 213
row1[6] = -x * u - 214
row1[7] = -y * u - 215●
a.push(row1) - 216●
b.push(u) - 217
// 第二行 - 218●
let row2 : Array[Float] = Array::make(8, 0.0F) - 219
row2[3] = x - 220
row2[4] = y - 221
row2[5] = 1.0F - 222
row2[6] = -x * v - 223
row2[7] = -y * v - 224●
a.push(row2) - 225●
b.push(v) - 226
} - 227
// 高斯消元解 8x8 方程组 - 228●
gauss_elimination(a, b, 8) - 229
} - 230
- 231
///| - 232
fn gauss_elimination( - 233
a : Array[Array[Float]], - 234
b : Array[Float], - 235
n : Int32, - 236
) -> Array[Float] { - 237
// 前向消元 - 238●
for col in 0..<n { - 239
// 找主元 - 240●
let mut max_row = col - 241●
let mut max_val = a[col][col].abs() - 242
for row in (col + 1)..<n { - 243●
if a[row][col].abs() > max_val { - 244●
max_val = a[row][col].abs() - 245
max_row = row - 246
} - 247
} - 248
if max_val < 0.0000000001F { - 249○
return [] - 250
} - 251
// 交换行 - 252
if max_row != col { - 253●
let tmp = a[col] - 254
a[col] = a[max_row] - 255
a[max_row] = tmp - 256
let tmpb = b[col] - 257
b[col] = b[max_row] - 258
b[max_row] = tmpb - 259
} - 260
// 消元 - 261
for row in (col + 1)..<n { - 262●
let factor = a[row][col] / a[col][col] - 263
for j in col..<n { - 264●
a[row][j] -= factor * a[col][j] - 265
} - 266
b[row] -= factor * b[col] - 267
} - 268
} - 269
// 回代 - 270●
let x : Array[Float] = Array::make(n, 0.0F) - 271
for ii in 0..<n { - 272●
let i = n - 1 - ii - 273
let mut sum = b[i] - 274
for j in (i + 1)..<n { - 275●
sum -= a[i][j] * x[j] - 276
} - 277
x[i] = sum / a[i][i] - 278
} - 279
x - 280
} - 281
- 282
///| - 283
fn reprojection_error( - 284
h : Array[Float], - 285
qx : Float, - 286
qy : Float, - 287
tx : Float, - 288
ty : Float, - 289
) -> Float { - 290
// h = [h11, h12, h13, h21, h22, h23, h31, h32] - 291●
let denom = h[6] * qx + h[7] * qy + 1.0F - 292●
if denom.abs() < 0.0000000001F { - 293○
return 10000000000.0F - 294
} - 295
let pu = (h[0] * qx + h[1] * qy + h[2]) / denom - 296
let pv = (h[3] * qx + h[4] * qy + h[5]) / denom - 297
let du = pu - tx - 298
let dv = pv - ty - 299●
(du * du + dv * dv).sqrt() - 300
}