image.process\feature\orb.mbt

91.5% · 107 / 117 points · 392 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/// # ORB 特征 orb
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// ORB 特征检测与描述(纯 MoonBit)
  7. 7// Oriented FAST and Rotated BRIEF
  8. 8// 参考: https://docs.opencv.org/4.x/d5/d3c/classcv_1_1Feature2D.html
  9. 9
  10. 10///|
  11. 11/// ORB 关键点:位置 + 响应 + 方向
  12. 12pub(all) struct OrbKeyPoint {
  13. 13 x : Int32
  14. 14 y : Int32
  15. 15 response : Float
  16. 16 angle : Float // 方向角(弧度)
  17. 17}
  18. 18
  19. 19///|
  20. 20/// ORB 描述子:256 位二进制描述(32 个 Int)
  21. 21pub(all) struct OrbDescriptor {
  22. 22 kp : OrbKeyPoint
  23. 23 data : Array[Int32] // 32 个 Int,每个 32 位,共 256 位
  24. 24}
  25. 25
  26. 26///|
  27. 27/// 特征匹配结果
  28. 28pub(all) struct DescriptorMatch {
  29. 29 query_idx : Int32
  30. 30 train_idx : Int32
  31. 31 distance : Int32 // 汉明距离
  32. 32}
  33. 33
  34. 34// ==================== FAST 角点检测 ====================
  35. 35
  36. 36///|
  37. 37/// FAST-9 圆周偏移(半径 3,16 个点)
  38. 38let fast_offsets : Array[(Int32, Int32)] = [
  39. 39 (0, -3),
  40. 40 (1, -3),
  41. 41 (2, -2),
  42. 42 (3, -1),
  43. 43 (3, 0),
  44. 44 (3, 1),
  45. 45 (2, 2),
  46. 46 (1, 3),
  47. 47 (0, 3),
  48. 48 (-1, 3),
  49. 49 (-2, 2),
  50. 50 (-3, 1),
  51. 51 (-3, 0),
  52. 52 (-3, -1),
  53. 53 (-2, -2),
  54. 54 (-1, -3),
  55. 55]
  56. 56
  57. 57///|
  58. 58/// FAST-9 角点检测
  59. 59fn fast_detect(
  60. 60 gray : Array[Int32],
  61. 61 w : Int32,
  62. 62 h : Int32,
  63. 63 threshold : Int32,
  64. 64) -> Array[OrbKeyPoint] {
  65. 65● let corners : Array[OrbKeyPoint] = []
  66. 66 for y in 3..<(h - 3) {
  67. 67● for x in 3..<(w - 3) {
  68. 68● let p = gray[y * w + x]
  69. 69 let high_thresh = p + threshold
  70. 70 let low_thresh = p - threshold
  71. 71 // 读取圆周 16 个像素
  72. 72● let vals : Array[Int32] = Array::make(16, 0)
  73. 73 for i in 0..<16 {
  74. 74● let (dx, dy) = fast_offsets[i]
  75. 75 vals[i] = gray[(y + dy) * w + (x + dx)]
  76. 76 }
  77. 77 // 检查是否有 9 个连续 brighter 或 darker
  78. 78● let is_corner = check_fast9(vals, high_thresh, low_thresh)
  79. 79 if is_corner {
  80. 80 // 计算方向
  81. 81● let angle = compute_orientation(gray, w, h, x, y)
  82. 82● corners.push(OrbKeyPoint::{ x, y, response: 1.0F, angle, })
  83. 83 }
  84. 84 }
  85. 85 }
  86. 86 corners
  87. 87}
  88. 88
  89. 89///|
  90. 90/// 检查 FAST-9 条件:圆周上是否有 9 个连续像素都 > high 或都 < low
  91. 91fn check_fast9(vals : Array[Int32], high : Int32, low : Int32) -> Bool {
  92. 92 // 将 16 个点复制两遍以处理环绕
  93. 93● let brighter : Array[Bool] = Array::make(32, false)
  94. 94● let darker : Array[Bool] = Array::make(32, false)
  95. 95 for i in 0..<16 {
  96. 96● brighter[i] = vals[i] > high
  97. 97 darker[i] = vals[i] < low
  98. 98 brighter[i + 16] = brighter[i]
  99. 99 darker[i + 16] = darker[i]
  100. 100 }
  101. 101 // 检查 9 连续
  102. 102 let mut b_run = 0
  103. 103 let mut d_run = 0
  104. 104 for i in 0..<32 {
  105. 105● if brighter[i] {
  106. 106● b_run += 1
  107. 107 if b_run >= 9 {
  108. 108● return true
  109. 109 }
  110. 110 } else {
  111. 111● b_run = 0
  112. 112 }
  113. 113 if darker[i] {
  114. 114● d_run += 1
  115. 115 if d_run >= 9 {
  116. 116● return true
  117. 117 }
  118. 118 } else {
  119. 119● d_run = 0
  120. 120 }
  121. 121 }
  122. 122 false
  123. 123}
  124. 124
  125. 125///|
  126. 126/// 计算关键点方向(图像矩质心法)
  127. 127/// 方向角与矩 θ = atan2(m01, m10), m_pq = Σ x^p * y^q * I(x,y)
  128. 128fn compute_orientation(
  129. 129 gray : Array[Int32],
  130. 130 w : Int32,
  131. 131 h : Int32,
  132. 132 cx : Int32,
  133. 133 cy : Int32,
  134. 134) -> Float {
  135. 135● let r = 15 // 取 31x31 patch
  136. 136 let mut m01 = 0.0F
  137. 137 let mut m10 = 0.0F
  138. 138 for dy in -r..<=r {
  139. 139● let y = cy + dy
  140. 140 if y < 0 || y >= h {
  141. 141● continue
  142. 142 }
  143. 143 for dx in -r..<=r {
  144. 144● let x = cx + dx
  145. 145 if x < 0 || x >= w {
  146. 146● continue
  147. 147 }
  148. 148● let v = Float::from_int(gray[y * w + x])
  149. 149● m01 += Float::from_int(dy) * v
  150. 150● m10 += Float::from_int(dx) * v
  151. 151 }
  152. 152 }
  153. 153● Float::from_double(@math.atan2(m01.to_double(), m10.to_double()))
  154. 154}
  155. 155
  156. 156// ==================== BRIEF 描述子 ====================
  157. 157
  158. 158///|
  159. 159/// 生成 BRIEF 采样点对(256 对)
  160. 160/// 使用固定伪随机模式(基于质心高斯分布)
  161. 161fn brief_pattern() -> Array[(Float, Float, Float, Float)] {
  162. 162 // 256 个点对 (x1, y1, x2, y2),相对于关键点中心
  163. 163 // 使用固定模式确保可重复性
  164. 164● let pairs : Array[(Float, Float, Float, Float)] = []
  165. 165 // 使用简单的 LCG 伪随机生成器
  166. 166 let mut seed = 12345
  167. 167 fn next_rand() -> Int32 {
  168. 168● seed = (seed * 1103515245 + 12345) & 0x7FFFFFFF
  169. 169 seed
  170. 170 }
  171. 171 for _ in 0..<256 {
  172. 172● let x1 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F
  173. 173● let y1 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F
  174. 174● let x2 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F
  175. 175● let y2 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F
  176. 176● pairs.push((x1, y1, x2, y2))
  177. 177 }
  178. 178 pairs
  179. 179}
  180. 180
  181. 181///|
  182. 182/// 计算 rBRIEF 描述子(旋转后的 BRIEF)
  183. 183fn compute_brief(
  184. 184 gray : Array[Int32],
  185. 185 w : Int32,
  186. 186 h : Int32,
  187. 187 kp : OrbKeyPoint,
  188. 188 pattern : Array[(Float, Float, Float, Float)],
  189. 189) -> Array[Int32] {
  190. 190● let desc : Array[Int32] = Array::make(32, 0)
  191. 191● let cos_a = Float::from_double(@math.cos(kp.angle.to_double()))
  192. 192● let sin_a = Float::from_double(@math.sin(kp.angle.to_double()))
  193. 193 for i in 0..<256 {
  194. 194● let (x1, y1, x2, y2) = pattern[i]
  195. 195 // 旋转采样点
  196. 196 let rx1 = x1 * cos_a - y1 * sin_a
  197. 197 let ry1 = x1 * sin_a + y1 * cos_a
  198. 198 let rx2 = x2 * cos_a - y2 * sin_a
  199. 199 let ry2 = x2 * sin_a + y2 * cos_a
  200. 200 // 采样像素值(双线性插值)
  201. 201● let v1 = sample_bilinear(gray, w, h, kp.x, kp.y, rx1, ry1)
  202. 202● let v2 = sample_bilinear(gray, w, h, kp.x, kp.y, rx2, ry2)
  203. 203 // 二进制测试
  204. 204 if v1 < v2 {
  205. 205● let word = i / 32
  206. 206 let bit = i % 32
  207. 207 desc[word] = desc[word] | (1 << bit)
  208. 208 }
  209. 209 }
  210. 210 desc
  211. 211}
  212. 212
  213. 213///|
  214. 214/// 双线性插值采样
  215. 215fn sample_bilinear(
  216. 216 gray : Array[Int32],
  217. 217 w : Int32,
  218. 218 h : Int32,
  219. 219 cx : Int32,
  220. 220 cy : Int32,
  221. 221 dx : Float,
  222. 222 dy : Float,
  223. 223) -> Int32 {
  224. 224● let fx = Float::from_int(cx) + dx
  225. 225● let fy = Float::from_int(cy) + dy
  226. 226● let x0 = fx.to_int()
  227. 227● let y0 = fy.to_int()
  228. 228 let x1 = x0 + 1
  229. 229 let y1 = y0 + 1
  230. 230● let x0c = x0.clamp(min=0, max=w - 1)
  231. 231● let x1c = x1.clamp(min=0, max=w - 1)
  232. 232● let y0c = y0.clamp(min=0, max=h - 1)
  233. 233● let y1c = y1.clamp(min=0, max=h - 1)
  234. 234 let p00 = gray[y0c * w + x0c]
  235. 235 let p01 = gray[y0c * w + x1c]
  236. 236 let p10 = gray[y1c * w + x0c]
  237. 237 let p11 = gray[y1c * w + x1c]
  238. 238● let wx = fx - Float::from_int(x0)
  239. 239● let wy = fy - Float::from_int(y0)
  240. 240● let v = Float::from_int(p00) * (1.0F - wx) * (1.0F - wy) +
  241. 241● Float::from_int(p01) * wx * (1.0F - wy) +
  242. 242● Float::from_int(p10) * (1.0F - wx) * wy +
  243. 243● Float::from_int(p11) * wx * wy
  244. 244● v.to_int()
  245. 245}
  246. 246
  247. 247// ==================== 灰度转换 ====================
  248. 248
  249. 249///|
  250. 250fn to_gray_orb(img : @types.Image) -> (Array[Int32], Int32, Int32) {
  251. 251● let w = img.width
  252. 252 let h = img.height
  253. 253 let ch = img.channels
  254. 254 let n = w * h
  255. 255● let gray : Array[Int32] = Array::make(n, 0)
  256. 256 for i in 0..<n {
  257. 257● if ch >= 3 {
  258. 258● let r = img.data[i * ch].to_int()
  259. 259● let g = img.data[i * ch + 1].to_int()
  260. 260● let b = img.data[i * ch + 2].to_int()
  261. 261 gray[i] = (r * 299 + g * 587 + b * 114) / 1000
  262. 262 } else {
  263. 263● gray[i] = img.data[i * ch].to_int()
  264. 264 }
  265. 265 }
  266. 266 (gray, w, h)
  267. 267}
  268. 268
  269. 269// ==================== 公开 API ====================
  270. 270
  271. 271///|
  272. 272/// ORB 特征检测。
  273. 273/// 检测 FAST 关键点并计算 rBRIEF 描述子。
  274. 274/// max_features 控制最大特征数,threshold 为 FAST 阈值。
  275. 275pub fn orb_detect(
  276. 276 img : @types.Image,
  277. 277 max_features~ : Int32 = 500,
  278. 278 threshold~ : Int32 = 20,
  279. 279) -> Array[OrbDescriptor] raise @types.LoadError {
  280. 280 // 输入验证
  281. 281● if img.width <= 0 || img.height <= 0 {
  282. 282○ raise @types.LoadError::DecodeFailed(
  283. 283 "orb_detect: 图像尺寸必须大于0",
  284. 284 )
  285. 285 }
  286. 286 if img.width < 7 || img.height < 7 {
  287. 287● raise @types.LoadError::DecodeFailed(
  288. 288 "orb_detect: ORB 需要至少 7x7 图像",
  289. 289 )
  290. 290 }
  291. 291 if img.channels < 1 || img.channels > 4 {
  292. 292○ raise @types.LoadError::DecodeFailed(
  293. 293 "orb_detect: 通道数必须在1-4之间",
  294. 294 )
  295. 295 }
  296. 296 let expected_size = img.width * img.height * img.channels
  297. 297● if img.data.length() != expected_size {
  298. 298○ raise @types.LoadError::DecodeFailed(
  299. 299 "orb_detect: 数据大小不匹配,期望 " +
  300. 300○ expected_size.to_string() +
  301. 301 ",实际 " +
  302. 302○ img.data.length().to_string(),
  303. 303 )
  304. 304 }
  305. 305 if max_features <= 0 {
  306. 306○ raise @types.LoadError::DecodeFailed(
  307. 307 "orb_detect: max_features必须大于0",
  308. 308 )
  309. 309 }
  310. 310 if threshold <= 0 || threshold > 255 {
  311. 311○ raise @types.LoadError::DecodeFailed(
  312. 312 "orb_detect: threshold必须在1-255范围内",
  313. 313 )
  314. 314 }
  315. 315● let (gray, w, h) = to_gray_orb(img)
  316. 316 // FAST 检测
  317. 317● let keypoints = fast_detect(gray, w, h, threshold)
  318. 318 // 限制特征数:取前 max_features 个
  319. 319● let kps = if keypoints.length() > max_features {
  320. 320● keypoints[0:max_features]
  321. 321 } else {
  322. 322● keypoints
  323. 323 }
  324. 324 // 计算 BRIEF 描述子
  325. 325● let pattern = brief_pattern()
  326. 326 let descriptors : Array[OrbDescriptor] = []
  327. 327 for kp in kps {
  328. 328● let desc = compute_brief(gray, w, h, kp, pattern)
  329. 329● descriptors.push(OrbDescriptor::{ kp, data: desc, })
  330. 330 }
  331. 331 descriptors
  332. 332}
  333. 333
  334. 334///|
  335. 335/// ORB 描述子汉明距离
  336. 336pub fn orb_hamming(d1 : OrbDescriptor, d2 : OrbDescriptor) -> Int32 {
  337. 337● let mut dist = 0
  338. 338 for i in 0..<32 {
  339. 339● let xor = d1.data[i] ^ d2.data[i]
  340. 340 // 计算位计数
  341. 341 let mut bits = xor
  342. 342 bits = (bits & 0x55555555) + ((bits >> 1) & 0x55555555)
  343. 343 bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333)
  344. 344 bits = (bits & 0x0F0F0F0F) + ((bits >> 4) & 0x0F0F0F0F)
  345. 345 bits = (bits & 0x00FF00FF) + ((bits >> 8) & 0x00FF00FF)
  346. 346 bits = (bits & 0x0000FFFF) + ((bits >> 16) & 0x0000FFFF)
  347. 347 dist += bits
  348. 348 }
  349. 349 dist
  350. 350}
  351. 351
  352. 352///|
  353. 353/// ORB 特征匹配。
  354. 354/// 对 query 中每个描述子,找 train 中汉明距离最小的匹配。
  355. 355/// max_distance 为最大允许距离(默认 64)。
  356. 356pub fn orb_match(
  357. 357 query : Array[OrbDescriptor],
  358. 358 train : Array[OrbDescriptor],
  359. 359 max_distance~ : Int32 = 64,
  360. 360) -> Array[DescriptorMatch] raise @types.LoadError {
  361. 361 // 参数验证
  362. 362● if query.length() == 0 {
  363. 363● raise @types.LoadError::DecodeFailed("orb_match: query数组不能为空")
  364. 364 }
  365. 365● if train.length() == 0 {
  366. 366○ raise @types.LoadError::DecodeFailed("orb_match: train数组不能为空")
  367. 367 }
  368. 368 if max_distance < 0 {
  369. 369○ raise @types.LoadError::DecodeFailed("orb_match: max_distance必须 >= 0")
  370. 370 }
  371. 371
  372. 372 let matches : Array[DescriptorMatch] = []
  373. 373● for i in 0..<query.length() {
  374. 374● let mut best_j = -1
  375. 375 let mut best_dist = max_distance + 1
  376. 376● for j in 0..<train.length() {
  377. 377● let dist = orb_hamming(query[i], train[j])
  378. 378 if dist < best_dist {
  379. 379● best_dist = dist
  380. 380 best_j = j
  381. 381 }
  382. 382 }
  383. 383 if best_j >= 0 && best_dist <= max_distance {
  384. 384● matches.push(DescriptorMatch::{
  385. 385 query_idx: i,
  386. 386 train_idx: best_j,
  387. 387 distance: best_dist,
  388. 388 })
  389. 389 }
  390. 390 }
  391. 391 matches
  392. 392}