image.vision\slam\slam_system.mbt

82.3% · 79 / 96 points · 587 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/// # SLAM 系统 slam/slam_system
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// SLAM 同时定位与地图构建(v31.0.0)
  7. 7// 特征点跟踪、位姿估计、地图构建、回环检测、优化
  8. 8
  9. 9///|
  10. 10/// SLAM 算法类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq, @debug.Debug)
  13. 13#non_exhaustive
  14. 14pub(all) enum SLAMAlgorithm {
  15. 15 MonoSLAM
  16. 16 ORBSLAM
  17. 17 LSD_SLAM
  18. 18 SVO
  19. 19 DSO
  20. 20 PTAM
  21. 21 KinectFusion
  22. 22 ElasticFusion
  23. 23 Unknown
  24. 24}
  25. 25
  26. 26///|
  27. 27pub extend SLAMAlgorithm with @debug.Debug::{to_repr}
  28. 28
  29. 29///|
  30. 30pub extend SLAMAlgorithm with Eq::{not_equal, equal}
  31. 31
  32. 32///|
  33. 33/// 相机位姿
  34. 34#derive(Eq, @debug.Debug)
  35. 35pub(all) struct CameraPose {
  36. 36 position : Array[Double]
  37. 37 rotation : Array[Double]
  38. 38 timestamp : Double
  39. 39 confidence : Double
  40. 40}
  41. 41
  42. 42///|
  43. 43pub extend CameraPose with Eq::{not_equal, equal}
  44. 44
  45. 45///|
  46. 46pub extend CameraPose with @debug.Debug::{to_repr}
  47. 47
  48. 48///|
  49. 49/// 3D 地图点
  50. 50#derive(Eq, @debug.Debug)
  51. 51pub(all) struct MapPoint {
  52. 52 position : Array[Double]
  53. 53 color : Array[Int32]
  54. 54 normal : Array[Double]
  55. 55 descriptor : Array[Double]
  56. 56 num_observations : Int32
  57. 57 is_outlier : Bool
  58. 58}
  59. 59
  60. 60///|
  61. 61pub extend MapPoint with Eq::{not_equal, equal}
  62. 62
  63. 63///|
  64. 64pub extend MapPoint with @debug.Debug::{to_repr}
  65. 65
  66. 66///|
  67. 67/// 关键帧
  68. 68#derive(Eq, @debug.Debug)
  69. 69pub(all) struct KeyFrame {
  70. 70 pose : CameraPose
  71. 71 image : @types.Image
  72. 72 features : Array[Array[Double]]
  73. 73 descriptors : Array[Array[Double]]
  74. 74 map_points : Array[Int32]
  75. 75 timestamp : Double
  76. 76 is_loop_closure : Bool
  77. 77}
  78. 78
  79. 79///|
  80. 80pub extend KeyFrame with Eq::{not_equal, equal}
  81. 81
  82. 82///|
  83. 83pub extend KeyFrame with @debug.Debug::{to_repr}
  84. 84
  85. 85///|
  86. 86/// SLAM 状态
  87. 87#derive(Eq, @debug.Debug)
  88. 88pub(all) struct SLAMState {
  89. 89 current_pose : CameraPose
  90. 90 trajectory : Array[CameraPose]
  91. 91 map_points : Array[MapPoint]
  92. 92 keyframes : Array[KeyFrame]
  93. 93 num_frames_processed : Int32
  94. 94 num_lost_frames : Int32
  95. 95 is_tracking : Bool
  96. 96 is_mapping : Bool
  97. 97 processing_time_ms : Double
  98. 98}
  99. 99
  100. 100///|
  101. 101pub extend SLAMState with Eq::{not_equal, equal}
  102. 102
  103. 103///|
  104. 104pub extend SLAMState with @debug.Debug::{to_repr}
  105. 105
  106. 106///|
  107. 107/// SLAM 配置
  108. 108#derive(Eq, @debug.Debug)
  109. 109pub(all) struct SLAMConfig {
  110. 110 algorithm : SLAMAlgorithm
  111. 111 feature_threshold : Double
  112. 112 max_features : Int32
  113. 113 keyframe_interval : Int32
  114. 114 min_parallax : Double
  115. 115 use_loop_closure : Bool
  116. 116 use_bundle_adjustment : Bool
  117. 117 camera_fx : Double
  118. 118 camera_fy : Double
  119. 119 camera_cx : Double
  120. 120 camera_cy : Double
  121. 121}
  122. 122
  123. 123///|
  124. 124pub extend SLAMConfig with Eq::{not_equal, equal}
  125. 125
  126. 126///|
  127. 127pub extend SLAMConfig with @debug.Debug::{to_repr}
  128. 128
  129. 129///|
  130. 130/// 特征跟踪结果
  131. 131#derive(Eq, @debug.Debug)
  132. 132pub(all) struct FeatureTrackingResult {
  133. 133 tracked_features : Array[Array[Double]]
  134. 134 num_tracked : Int32
  135. 135 num_lost : Int32
  136. 136 parallax : Double
  137. 137 is_keyframe : Bool
  138. 138}
  139. 139
  140. 140///|
  141. 141pub extend FeatureTrackingResult with Eq::{not_equal, equal}
  142. 142
  143. 143///|
  144. 144pub extend FeatureTrackingResult with @debug.Debug::{to_repr}
  145. 145
  146. 146///|
  147. 147/// 回环检测结果
  148. 148#derive(Eq, @debug.Debug)
  149. 149pub(all) struct LoopClosureResult {
  150. 150 is_loop_detected : Bool
  151. 151 loop_frame_index : Int32
  152. 152 similarity_score : Double
  153. 153 transformation : Array[Double]
  154. 154 num_inliers : Int32
  155. 155}
  156. 156
  157. 157///|
  158. 158pub extend LoopClosureResult with Eq::{not_equal, equal}
  159. 159
  160. 160///|
  161. 161pub extend LoopClosureResult with @debug.Debug::{to_repr}
  162. 162
  163. 163///|
  164. 164/// 创建默认 SLAM 配置
  165. 165pub fn create_default_slam_config() -> SLAMConfig {
  166. 166● SLAMConfig::{
  167. 167 algorithm: SLAMAlgorithm::ORBSLAM,
  168. 168 feature_threshold: 20.0,
  169. 169 max_features: 1000,
  170. 170 keyframe_interval: 5,
  171. 171 min_parallax: 10.0,
  172. 172 use_loop_closure: true,
  173. 173 use_bundle_adjustment: true,
  174. 174 camera_fx: 500.0,
  175. 175 camera_fy: 500.0,
  176. 176 camera_cx: 320.0,
  177. 177 camera_cy: 240.0,
  178. 178 }
  179. 179}
  180. 180
  181. 181///|
  182. 182/// 检测特征点(简化版:Harris 角点)
  183. 183pub fn detect_features_slam(
  184. 184 img : @types.Image,
  185. 185 max_features : Int32,
  186. 186 threshold : Double,
  187. 187) -> Array[Array[Double]] {
  188. 188● let w = img.width
  189. 189 let h = img.height
  190. 190 let features : Array[Array[Double]] = []
  191. 191
  192. 192 for y in 1..<(h - 1) {
  193. 193● for x in 1..<(w - 1) {
  194. 194● let idx = y * w + x
  195. 195● let gx = img.data[idx + 1].to_double() - img.data[idx - 1].to_double()
  196. 196● let gy = img.data[idx + w].to_double() - img.data[idx - w].to_double()
  197. 197 let response = gx * gx + gy * gy
  198. 198
  199. 199● if response > threshold && features.length() < max_features {
  200. 200● features.push([x.to_double(), y.to_double(), response])
  201. 201 }
  202. 202 }
  203. 203 }
  204. 204
  205. 205 features
  206. 206}
  207. 207
  208. 208///|
  209. 209/// 特征点跟踪(简化版:基于光流的块匹配)
  210. 210pub fn track_features_slam(
  211. 211 prev_img : @types.Image,
  212. 212 curr_img : @types.Image,
  213. 213 prev_features : Array[Array[Double]],
  214. 214 search_radius : Int32,
  215. 215) -> FeatureTrackingResult {
  216. 216● let w = prev_img.width
  217. 217 let h = prev_img.height
  218. 218 let tracked : Array[Array[Double]] = []
  219. 219 let mut num_lost = 0
  220. 220 let mut total_parallax = 0.0
  221. 221
  222. 222 for feat in prev_features {
  223. 223● let px = feat[0].to_int()
  224. 224● let py = feat[1].to_int()
  225. 225 let mut best_x = px
  226. 226 let mut best_y = py
  227. 227 let mut best_score = 1000000.0
  228. 228
  229. 229 for dy in -search_radius..<(search_radius + 1) {
  230. 230● for dx in -search_radius..<(search_radius + 1) {
  231. 231● let nx = px + dx
  232. 232 let ny = py + dy
  233. 233 if nx >= 2 && nx < w - 2 && ny >= 2 && ny < h - 2 {
  234. 234 // 计算块匹配误差(简化版:中心像素差)
  235. 235● let prev_pixel = prev_img.data[py * w + px].to_double()
  236. 236● let curr_pixel = curr_img.data[ny * w + nx].to_double()
  237. 237● let diff = (prev_pixel - curr_pixel).abs()
  238. 238 if diff < best_score {
  239. 239● best_score = diff
  240. 240 best_x = nx
  241. 241 best_y = ny
  242. 242 }
  243. 243 }
  244. 244 }
  245. 245 }
  246. 246
  247. 247 if best_score < 50.0 {
  248. 248● let dx = (best_x - px).to_double()
  249. 249● let dy = (best_y - py).to_double()
  250. 250● let parallax = (dx * dx + dy * dy).sqrt()
  251. 251 total_parallax += parallax
  252. 252● tracked.push([best_x.to_double(), best_y.to_double(), parallax])
  253. 253 } else {
  254. 254○ num_lost += 1
  255. 255 }
  256. 256 }
  257. 257
  258. 258● let avg_parallax = if tracked.length() > 0 {
  259. 259● total_parallax / tracked.length().to_double()
  260. 260 } else {
  261. 261● 0.0
  262. 262 }
  263. 263
  264. 264 FeatureTrackingResult::{
  265. 265 tracked_features: tracked,
  266. 266● num_tracked: tracked.length(),
  267. 267 num_lost,
  268. 268 parallax: avg_parallax,
  269. 269● is_keyframe: avg_parallax > 10.0 && tracked.length() > 50,
  270. 270 }
  271. 271}
  272. 272
  273. 273///|
  274. 274/// 估计相机位姿(简化版:基于特征点视差)
  275. 275pub fn estimate_camera_pose(
  276. 276 tracking_result : FeatureTrackingResult,
  277. 277 config : SLAMConfig,
  278. 278 prev_pose : CameraPose,
  279. 279) -> CameraPose {
  280. 280● ignore(config)
  281. 281 // 简化的位姿估计:基于平均视差
  282. 282 let avg_parallax = tracking_result.parallax
  283. 283 let forward_motion = avg_parallax * 0.01
  284. 284 let dz = forward_motion
  285. 285
  286. 286 CameraPose::{
  287. 287 position: [
  288. 288 prev_pose.position[0],
  289. 289 prev_pose.position[1],
  290. 290 prev_pose.position[2] + dz,
  291. 291 ],
  292. 292 rotation: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
  293. 293 timestamp: prev_pose.timestamp + 0.033,
  294. 294● confidence: tracking_result.num_tracked.to_double() /
  295. 295● (tracking_result.num_tracked + tracking_result.num_lost).to_double(),
  296. 296 }
  297. 297}
  298. 298
  299. 299///|
  300. 300/// 三角化 3D 点(简化版)
  301. 301pub fn triangulate_points(
  302. 302 features : Array[Array[Double]],
  303. 303 pose1 : CameraPose,
  304. 304 pose2 : CameraPose,
  305. 305 config : SLAMConfig,
  306. 306) -> Array[MapPoint] {
  307. 307● let points : Array[MapPoint] = []
  308. 308
  309. 309 for feat in features {
  310. 310● let x = feat[0]
  311. 311 let y = feat[1]
  312. 312
  313. 313 // 简化的三角化:基于视差估计深度
  314. 314● let disparity = (pose2.position[0] - pose1.position[0]).abs() + 0.001
  315. 315 let depth = config.camera_fx * 0.1 / disparity
  316. 316
  317. 317 // 反投影到 3D
  318. 318 let x3d = (x - config.camera_cx) * depth / config.camera_fx
  319. 319 let y3d = (y - config.camera_cy) * depth / config.camera_fy
  320. 320 let z3d = depth
  321. 321
  322. 322● points.push(MapPoint::{
  323. 323 position: [x3d, y3d, z3d],
  324. 324 color: [128, 128, 128],
  325. 325 normal: [0.0, 0.0, 1.0],
  326. 326 descriptor: [],
  327. 327 num_observations: 2,
  328. 328 is_outlier: false,
  329. 329 })
  330. 330 }
  331. 331
  332. 332 points
  333. 333}
  334. 334
  335. 335///|
  336. 336/// 回环检测(简化版:基于特征点数量相似度)
  337. 337pub fn detect_loop_closure(
  338. 338 current_features : Array[Array[Double]],
  339. 339 keyframes : Array[KeyFrame],
  340. 340 threshold : Double,
  341. 341) -> LoopClosureResult {
  342. 342● let mut best_score = 0.0
  343. 343 let mut best_index = -1
  344. 344
  345. 345● for i in 0..<keyframes.length() {
  346. 346○ let kf = keyframes[i]
  347. 347 // 简化的相似度:特征点数量比较
  348. 348○ let score = if kf.features.length() > 0 {
  349. 349○ current_features.length().to_double() / kf.features.length().to_double()
  350. 350 } else {
  351. 351○ 0.0
  352. 352 }
  353. 353
  354. 354 if score > best_score && score > threshold {
  355. 355○ best_score = score
  356. 356 best_index = i
  357. 357 }
  358. 358 }
  359. 359
  360. 360 if best_index >= 0 {
  361. 361○ LoopClosureResult::{
  362. 362 is_loop_detected: true,
  363. 363 loop_frame_index: best_index,
  364. 364 similarity_score: best_score,
  365. 365 transformation: [
  366. 366 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
  367. 367 1.0,
  368. 368 ],
  369. 369 num_inliers: 50,
  370. 370 }
  371. 371 } else {
  372. 372● LoopClosureResult::{
  373. 373 is_loop_detected: false,
  374. 374 loop_frame_index: -1,
  375. 375 similarity_score: 0.0,
  376. 376 transformation: [
  377. 377 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
  378. 378 1.0,
  379. 379 ],
  380. 380 num_inliers: 0,
  381. 381 }
  382. 382 }
  383. 383}
  384. 384
  385. 385///|
  386. 386/// 初始化 SLAM 系统
  387. 387pub fn initialize_slam(config : SLAMConfig) -> SLAMState {
  388. 388● ignore(config)
  389. 389 let initial_pose = CameraPose::{
  390. 390 position: [0.0, 0.0, 0.0],
  391. 391 rotation: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
  392. 392 timestamp: 0.0,
  393. 393 confidence: 1.0,
  394. 394 }
  395. 395
  396. 396 SLAMState::{
  397. 397 current_pose: initial_pose,
  398. 398 trajectory: [initial_pose],
  399. 399 map_points: [],
  400. 400 keyframes: [],
  401. 401 num_frames_processed: 0,
  402. 402 num_lost_frames: 0,
  403. 403 is_tracking: true,
  404. 404 is_mapping: true,
  405. 405 processing_time_ms: 0.0,
  406. 406 }
  407. 407}
  408. 408
  409. 409///|
  410. 410/// 处理单帧图像
  411. 411pub fn process_frame_slam(
  412. 412 state : SLAMState,
  413. 413 img : @types.Image,
  414. 414 config : SLAMConfig,
  415. 415) -> SLAMState {
  416. 416 // 检测特征点
  417. 417● let features = detect_features_slam(
  418. 418 img,
  419. 419 config.max_features,
  420. 420 config.feature_threshold,
  421. 421 )
  422. 422
  423. 423 // 如果有关键帧,进行特征跟踪
  424. 424● if state.keyframes.length() > 0 {
  425. 425● let last_kf = state.keyframes[state.keyframes.length() - 1]
  426. 426● let tracking_result = track_features_slam(
  427. 427 last_kf.image,
  428. 428 img,
  429. 429 last_kf.features,
  430. 430 16,
  431. 431 )
  432. 432
  433. 433 // 估计位姿
  434. 434● let new_pose = estimate_camera_pose(
  435. 435 tracking_result,
  436. 436 config,
  437. 437 state.current_pose,
  438. 438 )
  439. 439
  440. 440 // 如果是关键帧,添加到地图
  441. 441 if tracking_result.is_keyframe {
  442. 442● let new_kf = KeyFrame::{
  443. 443 pose: new_pose,
  444. 444 image: img,
  445. 445 features,
  446. 446 descriptors: [],
  447. 447 map_points: [],
  448. 448 timestamp: new_pose.timestamp,
  449. 449 is_loop_closure: false,
  450. 450 }
  451. 451
  452. 452 // 三角化新的地图点
  453. 453● let new_points = triangulate_points(
  454. 454 features,
  455. 455 last_kf.pose,
  456. 456 new_pose,
  457. 457 config,
  458. 458 )
  459. 459
  460. 460 let new_map_points = state.map_points
  461. 461 for p in new_points {
  462. 462● new_map_points.push(p)
  463. 463 }
  464. 464
  465. 465 let new_keyframes = state.keyframes
  466. 466● new_keyframes.push(new_kf)
  467. 467
  468. 468 let new_trajectory = state.trajectory
  469. 469● new_trajectory.push(new_pose)
  470. 470
  471. 471 SLAMState::{
  472. 472 current_pose: new_pose,
  473. 473 trajectory: new_trajectory,
  474. 474 map_points: new_map_points,
  475. 475 keyframes: new_keyframes,
  476. 476 num_frames_processed: state.num_frames_processed + 1,
  477. 477 num_lost_frames: state.num_lost_frames,
  478. 478 is_tracking: tracking_result.num_tracked > 20,
  479. 479 is_mapping: true,
  480. 480 processing_time_ms: 0.0,
  481. 481 }
  482. 482 } else {
  483. 483○ let new_trajectory = state.trajectory
  484. 484○ new_trajectory.push(new_pose)
  485. 485
  486. 486 SLAMState::{
  487. 487 current_pose: new_pose,
  488. 488 trajectory: new_trajectory,
  489. 489 map_points: state.map_points,
  490. 490 keyframes: state.keyframes,
  491. 491 num_frames_processed: state.num_frames_processed + 1,
  492. 492 num_lost_frames: if tracking_result.num_tracked < 20 {
  493. 493○ state.num_lost_frames + 1
  494. 494 } else {
  495. 495○ state.num_lost_frames
  496. 496 },
  497. 497 is_tracking: tracking_result.num_tracked > 20,
  498. 498 is_mapping: true,
  499. 499 processing_time_ms: 0.0,
  500. 500 }
  501. 501 }
  502. 502 } else {
  503. 503 // 第一帧:初始化为关键帧
  504. 504● let initial_kf = KeyFrame::{
  505. 505 pose: state.current_pose,
  506. 506 image: img,
  507. 507 features,
  508. 508 descriptors: [],
  509. 509 map_points: [],
  510. 510 timestamp: 0.0,
  511. 511 is_loop_closure: false,
  512. 512 }
  513. 513
  514. 514 SLAMState::{
  515. 515 current_pose: state.current_pose,
  516. 516 trajectory: state.trajectory,
  517. 517 map_points: state.map_points,
  518. 518 keyframes: [initial_kf],
  519. 519 num_frames_processed: state.num_frames_processed + 1,
  520. 520 num_lost_frames: state.num_lost_frames,
  521. 521 is_tracking: true,
  522. 522 is_mapping: true,
  523. 523 processing_time_ms: 0.0,
  524. 524 }
  525. 525 }
  526. 526}
  527. 527
  528. 528///|
  529. 529/// 生成 SLAM 报告
  530. 530pub fn slam_report_to_string(state : SLAMState) -> String {
  531. 531● let mut report = "## SLAM 系统报告\n\n"
  532. 532 report = report + "### 系统状态\n\n"
  533. 533 report = report + "| 指标 | 值 |\n|------|------|\n"
  534. 534 report = report +
  535. 535 "| 处理帧数 | " +
  536. 536● state.num_frames_processed.to_string() +
  537. 537 " |\n"
  538. 538 report = report +
  539. 539 "| 丢失帧数 | " +
  540. 540● state.num_lost_frames.to_string() +
  541. 541 " |\n"
  542. 542 report = report +
  543. 543 "| 关键帧数 | " +
  544. 544● state.keyframes.length().to_string() +
  545. 545 " |\n"
  546. 546 report = report +
  547. 547 "| 地图点数 | " +
  548. 548● state.map_points.length().to_string() +
  549. 549 " |\n"
  550. 550 report = report +
  551. 551 "| 轨迹长度 | " +
  552. 552● state.trajectory.length().to_string() +
  553. 553 " |\n"
  554. 554 report = report +
  555. 555 "| 跟踪状态 | " +
  556. 556◐ (if state.is_tracking { "跟踪中" } else { "丢失" }) +
  557. 557 " |\n"
  558. 558 report = report +
  559. 559 "| 建图状态 | " +
  560. 560◐ (if state.is_mapping { "建图中" } else { "暂停" }) +
  561. 561 " |\n\n"
  562. 562
  563. 563 report = report + "### 当前位姿\n\n"
  564. 564 report = report + "| 指标 | 值 |\n|------|------|\n"
  565. 565 report = report +
  566. 566 "| 位置 X | " +
  567. 567● state.current_pose.position[0].to_string() +
  568. 568 " |\n"
  569. 569 report = report +
  570. 570 "| 位置 Y | " +
  571. 571● state.current_pose.position[1].to_string() +
  572. 572 " |\n"
  573. 573 report = report +
  574. 574 "| 位置 Z | " +
  575. 575● state.current_pose.position[2].to_string() +
  576. 576 " |\n"
  577. 577 report = report +
  578. 578 "| 置信度 | " +
  579. 579● (state.current_pose.confidence * 100.0).to_string() +
  580. 580 "% |\n"
  581. 581 report = report +
  582. 582 "| 时间戳 | " +
  583. 583● state.current_pose.timestamp.to_string() +
  584. 584 "s |\n"
  585. 585
  586. 586 report
  587. 587}