image.process\feature\match.mbt

87.1% · 74 / 85 points · 300 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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