image.domain\registration\advanced_registration.mbt

96.6% · 143 / 148 points · 620 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/// # 高级配准 registration/advanced_registration
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 高级图像配准算法(v30.0.0)
  7. 7// 特征点匹配、变换估计、多模态配准、配准质量评估
  8. 8
  9. 9///|
  10. 10/// 配准算法类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq)
  13. 13#non_exhaustive
  14. 14pub(all) enum RegistrationAlgorithm {
  15. 15 PhaseCorrelation
  16. 16 FeatureBased
  17. 17 IntensityBased
  18. 18 MutualInformation
  19. 19 NormalizedCrossCorrelation
  20. 20 SumOfSquaredDifferences
  21. 21 OpticalFlow
  22. 22 Demons
  23. 23 Bspline
  24. 24 Unknown
  25. 25}
  26. 26
  27. 27///|
  28. 28pub extend RegistrationAlgorithm with Eq::{not_equal, equal}
  29. 29
  30. 30///|
  31. 31/// 变换类型
  32. 32/// `#non_exhaustive` 表示未来可能添加新构造器
  33. 33#derive(Eq)
  34. 34#non_exhaustive
  35. 35pub(all) enum TransformType {
  36. 36 Translation
  37. 37 Rigid
  38. 38 Similarity
  39. 39 Affine
  40. 40 Perspective
  41. 41 Polynomial
  42. 42 ThinPlateSpline
  43. 43 Bspline
  44. 44 Unknown
  45. 45}
  46. 46
  47. 47///|
  48. 48pub extend TransformType with Eq::{not_equal, equal}
  49. 49
  50. 50///|
  51. 51/// 配准结果
  52. 52pub(all) struct RegistrationResultAdvanced {
  53. 53 registered_image : @types.Image
  54. 54 algorithm : RegistrationAlgorithm
  55. 55 transform_type : TransformType
  56. 56 transform_matrix : Array[Double]
  57. 57 translation_x : Double
  58. 58 translation_y : Double
  59. 59 rotation_angle : Double
  60. 60 scale_x : Double
  61. 61 scale_y : Double
  62. 62 correlation : Double
  63. 63 mutual_information : Double
  64. 64 rmse : Double
  65. 65 processing_time_ms : Double
  66. 66 num_feature_points : Int32
  67. 67 num_inliers : Int32
  68. 68}
  69. 69
  70. 70///|
  71. 71/// 配准配置
  72. 72pub(all) struct RegistrationConfigAdvanced {
  73. 73 algorithm : RegistrationAlgorithm
  74. 74 transform_type : TransformType
  75. 75 max_iterations : Int32
  76. 76 convergence_threshold : Double
  77. 77 pyramid_levels : Int32
  78. 78 search_radius : Int32
  79. 79 use_multiresolution : Bool
  80. 80 use_robust_estimation : Bool
  81. 81}
  82. 82
  83. 83///|
  84. 84/// 特征点
  85. 85pub(all) struct FeaturePoint {
  86. 86 x : Double
  87. 87 y : Double
  88. 88 response : Double
  89. 89 orientation : Double
  90. 90 scale : Double
  91. 91 descriptor : Array[Double]
  92. 92}
  93. 93
  94. 94///|
  95. 95/// 特征匹配对
  96. 96pub(all) struct FeatureMatch {
  97. 97 point1 : FeaturePoint
  98. 98 point2 : FeaturePoint
  99. 99 distance : Double
  100. 100 is_inlier : Bool
  101. 101}
  102. 102
  103. 103///|
  104. 104/// 变换矩阵
  105. 105pub(all) struct TransformMatrix {
  106. 106 matrix : Array[Double]
  107. 107 transform_type : TransformType
  108. 108 width : Int32
  109. 109 height : Int32
  110. 110}
  111. 111
  112. 112///|
  113. 113/// 创建默认配准配置
  114. 114pub fn create_default_registration_config_advanced() -> RegistrationConfigAdvanced {
  115. 115● RegistrationConfigAdvanced::{
  116. 116 algorithm: RegistrationAlgorithm::PhaseCorrelation,
  117. 117 transform_type: TransformType::Translation,
  118. 118 max_iterations: 100,
  119. 119 convergence_threshold: 0.001,
  120. 120 pyramid_levels: 3,
  121. 121 search_radius: 32,
  122. 122 use_multiresolution: true,
  123. 123 use_robust_estimation: true,
  124. 124 }
  125. 125}
  126. 126
  127. 127///|
  128. 128/// 相位相关配准(平移估计)
  129. 129pub fn phase_correlation_registration(
  130. 130 img1 : @types.Image,
  131. 131 img2 : @types.Image,
  132. 132) -> RegistrationResultAdvanced {
  133. 133● let w = img1.width
  134. 134 let h = img1.height
  135. 135 let total = w * h
  136. 136
  137. 137 // 简化的相位相关:计算互相关
  138. 138 let mut max_corr = 0.0
  139. 139 let mut best_dx = 0
  140. 140 let mut best_dy = 0
  141. 141
  142. 142 // 搜索范围
  143. 143 let search_range = 32
  144. 144 for dy in -search_range..<(search_range + 1) {
  145. 145● for dx in -search_range..<(search_range + 1) {
  146. 146● let mut corr = 0.0
  147. 147 let mut count = 0
  148. 148 for y in 0..<h {
  149. 149● for x in 0..<w {
  150. 150● let nx = x + dx
  151. 151 let ny = y + dy
  152. 152 if nx >= 0 && nx < w && ny >= 0 && ny < h {
  153. 153● let p1 = img1.data[y * w + x].to_double()
  154. 154● let p2 = img2.data[ny * w + nx].to_double()
  155. 155 corr += p1 * p2
  156. 156 count += 1
  157. 157 }
  158. 158 }
  159. 159 }
  160. 160 if count > 0 {
  161. 161● corr /= count.to_double()
  162. 162 }
  163. 163 if corr > max_corr {
  164. 164● max_corr = corr
  165. 165 best_dx = dx
  166. 166 best_dy = dy
  167. 167 }
  168. 168 }
  169. 169 }
  170. 170
  171. 171 // 应用平移变换
  172. 172● let registered = apply_translation(img2, best_dx, best_dy)
  173. 173
  174. 174 // 计算 RMSE
  175. 175 let mut rmse = 0.0
  176. 176 for i in 0..<total {
  177. 177● let diff = img1.data[i].to_double() - registered.data[i].to_double()
  178. 178 rmse += diff * diff
  179. 179 }
  180. 180● rmse = (rmse / total.to_double()).sqrt()
  181. 181
  182. 182 RegistrationResultAdvanced::{
  183. 183 registered_image: registered,
  184. 184 algorithm: RegistrationAlgorithm::PhaseCorrelation,
  185. 185 transform_type: TransformType::Translation,
  186. 186 transform_matrix: [
  187. 187 1.0,
  188. 188 0.0,
  189. 189● best_dx.to_double(),
  190. 190 0.0,
  191. 191 1.0,
  192. 192● best_dy.to_double(),
  193. 193 0.0,
  194. 194 0.0,
  195. 195 1.0,
  196. 196 ],
  197. 197● translation_x: best_dx.to_double(),
  198. 198● translation_y: best_dy.to_double(),
  199. 199 rotation_angle: 0.0,
  200. 200 scale_x: 1.0,
  201. 201 scale_y: 1.0,
  202. 202 correlation: max_corr / 255.0,
  203. 203 mutual_information: 0.0,
  204. 204 rmse,
  205. 205 processing_time_ms: 0.0,
  206. 206 num_feature_points: 0,
  207. 207 num_inliers: 0,
  208. 208 }
  209. 209}
  210. 210
  211. 211///|
  212. 212/// 应用平移变换
  213. 213pub fn apply_translation(
  214. 214 img : @types.Image,
  215. 215 dx : Int32,
  216. 216 dy : Int32,
  217. 217) -> @types.Image {
  218. 218● let w = img.width
  219. 219 let h = img.height
  220. 220 let _ = w * h
  221. 221 let out : Array[Byte] = []
  222. 222
  223. 223 for y in 0..<h {
  224. 224● for x in 0..<w {
  225. 225● let src_x = x - dx
  226. 226 let src_y = y - dy
  227. 227 if src_x >= 0 && src_x < w && src_y >= 0 && src_y < h {
  228. 228● out.push(img.data[src_y * w + src_x])
  229. 229 } else {
  230. 230● out.push(b'\x00')
  231. 231 }
  232. 232 }
  233. 233 }
  234. 234
  235. 235 @types.Image::{
  236. 236 width: w,
  237. 237 height: h,
  238. 238 channels: img.channels,
  239. 239● data: Bytes::from_array(out),
  240. 240 }
  241. 241}
  242. 242
  243. 243///|
  244. 244/// 归一化互相关(NCC)
  245. 245pub fn normalized_cross_correlation(
  246. 246 img1 : @types.Image,
  247. 247 img2 : @types.Image,
  248. 248) -> Double {
  249. 249● let w = img1.width
  250. 250 let h = img1.height
  251. 251 let total = w * h
  252. 252
  253. 253 // 计算均值
  254. 254 let mut mean1 = 0.0
  255. 255 let mut mean2 = 0.0
  256. 256 for i in 0..<total {
  257. 257● mean1 += img1.data[i].to_double()
  258. 258● mean2 += img2.data[i].to_double()
  259. 259 }
  260. 260● mean1 /= total.to_double()
  261. 261● mean2 /= total.to_double()
  262. 262
  263. 263 // 计算 NCC
  264. 264 let mut numerator = 0.0
  265. 265 let mut denom1 = 0.0
  266. 266 let mut denom2 = 0.0
  267. 267 for i in 0..<total {
  268. 268● let p1 = img1.data[i].to_double() - mean1
  269. 269● let p2 = img2.data[i].to_double() - mean2
  270. 270 numerator += p1 * p2
  271. 271 denom1 += p1 * p1
  272. 272 denom2 += p2 * p2
  273. 273 }
  274. 274
  275. 275 if denom1 > 0.0 && denom2 > 0.0 {
  276. 276● numerator / (denom1.sqrt() * denom2.sqrt())
  277. 277 } else {
  278. 278○ 0.0
  279. 279 }
  280. 280}
  281. 281
  282. 282///|
  283. 283/// 互信息(Mutual Information)
  284. 284pub fn calculate_mutual_information(
  285. 285 img1 : @types.Image,
  286. 286 img2 : @types.Image,
  287. 287) -> Double {
  288. 288● let w = img1.width
  289. 289 let h = img1.height
  290. 290 let total = w * h
  291. 291 let bins = 64
  292. 292
  293. 293 // 联合直方图
  294. 294 let joint_hist : Array[Int32] = []
  295. 295 for _ in 0..<(bins * bins) {
  296. 296● joint_hist.push(0)
  297. 297 }
  298. 298
  299. 299 for i in 0..<total {
  300. 300● let b1 = img1.data[i].to_int() * bins / 256
  301. 301● let b2 = img2.data[i].to_int() * bins / 256
  302. 302 joint_hist[b1 * bins + b2] += 1
  303. 303 }
  304. 304
  305. 305 // 计算互信息
  306. 306 let mut mi = 0.0
  307. 307 for i in 0..<bins {
  308. 308● for j in 0..<bins {
  309. 309● let pxy = joint_hist[i * bins + j].to_double() / total.to_double()
  310. 310 if pxy > 0.0 {
  311. 311 // 计算边缘概率
  312. 312● let mut px = 0.0
  313. 313 let mut py = 0.0
  314. 314 for k in 0..<bins {
  315. 315● px += joint_hist[i * bins + k].to_double() / total.to_double()
  316. 316● py += joint_hist[k * bins + j].to_double() / total.to_double()
  317. 317 }
  318. 318 if px > 0.0 && py > 0.0 {
  319. 319● mi += pxy * (pxy / (px * py)) * 0.1 // 简化的 log
  320. 320 }
  321. 321 }
  322. 322 }
  323. 323 }
  324. 324
  325. 325 mi
  326. 326}
  327. 327
  328. 328///|
  329. 329/// Harris 角点检测(简化版)
  330. 330pub fn detect_harris_corners(
  331. 331 img : @types.Image,
  332. 332 threshold : Double,
  333. 333) -> Array[FeaturePoint] {
  334. 334● let w = img.width
  335. 335 let h = img.height
  336. 336 let points : Array[FeaturePoint] = []
  337. 337
  338. 338 // 计算梯度
  339. 339 for y in 1..<(h - 1) {
  340. 340● for x in 1..<(w - 1) {
  341. 341● let idx = y * w + x
  342. 342● let gx = img.data[idx + 1].to_double() - img.data[idx - 1].to_double()
  343. 343● let gy = img.data[idx + w].to_double() - img.data[idx - w].to_double()
  344. 344
  345. 345 // Harris 响应(简化版)
  346. 346 let response = gx * gx * gy * gy -
  347. 347 gx * gy * (gx * gy) * 0.04 -
  348. 348 (gx * gx + gy * gy) * (gx * gx + gy * gy) * 0.04
  349. 349
  350. 350 if response > threshold {
  351. 351● points.push(FeaturePoint::{
  352. 352● x: x.to_double(),
  353. 353● y: y.to_double(),
  354. 354 response,
  355. 355 orientation: 0.0,
  356. 356 scale: 1.0,
  357. 357 descriptor: [],
  358. 358 })
  359. 359 }
  360. 360 }
  361. 361 }
  362. 362
  363. 363 points
  364. 364}
  365. 365
  366. 366///|
  367. 367/// 特征点匹配(简化版:基于距离)
  368. 368pub fn match_feature_points(
  369. 369 points1 : Array[FeaturePoint],
  370. 370 points2 : Array[FeaturePoint],
  371. 371 max_distance : Double,
  372. 372) -> Array[FeatureMatch] {
  373. 373● let matches : Array[FeatureMatch] = []
  374. 374
  375. 375 for p1 in points1 {
  376. 376● let mut best_match : FeaturePoint = p1
  377. 377 let mut best_dist = max_distance
  378. 378 for p2 in points2 {
  379. 379● let dx = p1.x - p2.x
  380. 380 let dy = p1.y - p2.y
  381. 381● let dist = (dx * dx + dy * dy).sqrt()
  382. 382 if dist < best_dist {
  383. 383● best_dist = dist
  384. 384 best_match = p2
  385. 385 }
  386. 386 }
  387. 387 if best_dist < max_distance {
  388. 388● matches.push(FeatureMatch::{
  389. 389 point1: p1,
  390. 390 point2: best_match,
  391. 391 distance: best_dist,
  392. 392 is_inlier: true,
  393. 393 })
  394. 394 }
  395. 395 }
  396. 396
  397. 397 matches
  398. 398}
  399. 399
  400. 400///|
  401. 401/// 估计仿射变换(简化版:基于匹配对)
  402. 402pub fn estimate_affine_transform(
  403. 403 matches : Array[FeatureMatch],
  404. 404) -> TransformMatrix {
  405. 405 // 简化:使用前3个匹配对估计仿射变换
  406. 406● if matches.length() >= 3 {
  407. 407● let m1 = matches[0]
  408. 408 let m2 = matches[1]
  409. 409 let m3 = matches[2]
  410. 410
  411. 411 // 简化的仿射矩阵
  412. 412 let a = (m2.point2.x - m1.point2.x) / (m2.point1.x - m1.point1.x + 0.001)
  413. 413 let b = (m3.point2.y - m1.point2.y) / (m3.point1.y - m1.point1.y + 0.001)
  414. 414 let tx = m1.point2.x - a * m1.point1.x
  415. 415 let ty = m1.point2.y - b * m1.point1.y
  416. 416
  417. 417 TransformMatrix::{
  418. 418 matrix: [a, 0.0, tx, 0.0, b, ty, 0.0, 0.0, 1.0],
  419. 419 transform_type: TransformType::Affine,
  420. 420 width: 3,
  421. 421 height: 3,
  422. 422 }
  423. 423 } else {
  424. 424● TransformMatrix::{
  425. 425 matrix: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0],
  426. 426 transform_type: TransformType::Unknown,
  427. 427 width: 3,
  428. 428 height: 3,
  429. 429 }
  430. 430 }
  431. 431}
  432. 432
  433. 433///|
  434. 434/// 应用仿射变换
  435. 435pub fn apply_affine_transform(
  436. 436 img : @types.Image,
  437. 437 matrix : TransformMatrix,
  438. 438) -> @types.Image {
  439. 439● let w = img.width
  440. 440 let h = img.height
  441. 441 let _ = w * h
  442. 442 let out : Array[Byte] = []
  443. 443
  444. 444 let a = matrix.matrix[0]
  445. 445 let b = matrix.matrix[1]
  446. 446 let tx = matrix.matrix[2]
  447. 447 let c = matrix.matrix[3]
  448. 448 let d = matrix.matrix[4]
  449. 449 let ty = matrix.matrix[5]
  450. 450
  451. 451 for y in 0..<h {
  452. 452● for x in 0..<w {
  453. 453 // 逆变换
  454. 454● let src_x = (d * (x.to_double() - tx) - b * (y.to_double() - ty)) /
  455. 455 (a * d - b * c + 0.001)
  456. 456● let src_y = (-c * (x.to_double() - tx) + a * (y.to_double() - ty)) /
  457. 457 (a * d - b * c + 0.001)
  458. 458
  459. 459● let sx = src_x.to_int()
  460. 460● let sy = src_y.to_int()
  461. 461
  462. 462 if sx >= 0 && sx < w && sy >= 0 && sy < h {
  463. 463● out.push(img.data[sy * w + sx])
  464. 464 } else {
  465. 465● out.push(b'\x00')
  466. 466 }
  467. 467 }
  468. 468 }
  469. 469
  470. 470 @types.Image::{
  471. 471 width: w,
  472. 472 height: h,
  473. 473 channels: img.channels,
  474. 474● data: Bytes::from_array(out),
  475. 475 }
  476. 476}
  477. 477
  478. 478///|
  479. 479/// 基于特征的配准
  480. 480pub fn feature_based_registration(
  481. 481 img1 : @types.Image,
  482. 482 img2 : @types.Image,
  483. 483 config : RegistrationConfigAdvanced,
  484. 484) -> RegistrationResultAdvanced {
  485. 485● ignore(config)
  486. 486 // 检测特征点
  487. 487● let points1 = detect_harris_corners(img1, 100000.0)
  488. 488● let points2 = detect_harris_corners(img2, 100000.0)
  489. 489
  490. 490 // 匹配特征点
  491. 491● let matches = match_feature_points(points1, points2, 100.0)
  492. 492
  493. 493 // 估计变换
  494. 494● let transform = estimate_affine_transform(matches)
  495. 495
  496. 496 // 应用变换
  497. 497● let registered = apply_affine_transform(img2, transform)
  498. 498
  499. 499 // 计算质量指标
  500. 500● let correlation = normalized_cross_correlation(img1, registered)
  501. 501● let mi = calculate_mutual_information(img1, registered)
  502. 502
  503. 503 // 计算 RMSE
  504. 504 let w = img1.width
  505. 505 let h = img1.height
  506. 506 let total = w * h
  507. 507 let mut rmse = 0.0
  508. 508 for i in 0..<total {
  509. 509● let diff = img1.data[i].to_double() - registered.data[i].to_double()
  510. 510 rmse += diff * diff
  511. 511 }
  512. 512● rmse = (rmse / total.to_double()).sqrt()
  513. 513
  514. 514 RegistrationResultAdvanced::{
  515. 515 registered_image: registered,
  516. 516 algorithm: RegistrationAlgorithm::FeatureBased,
  517. 517 transform_type: TransformType::Affine,
  518. 518 transform_matrix: transform.matrix,
  519. 519 translation_x: transform.matrix[2],
  520. 520 translation_y: transform.matrix[5],
  521. 521 rotation_angle: 0.0,
  522. 522 scale_x: transform.matrix[0],
  523. 523 scale_y: transform.matrix[4],
  524. 524 correlation,
  525. 525 mutual_information: mi,
  526. 526 rmse,
  527. 527 processing_time_ms: 0.0,
  528. 528● num_feature_points: points1.length() + points2.length(),
  529. 529● num_inliers: matches.length(),
  530. 530 }
  531. 531}
  532. 532
  533. 533///|
  534. 534/// 图像配准(主入口)
  535. 535pub fn register_images_advanced(
  536. 536 img1 : @types.Image,
  537. 537 img2 : @types.Image,
  538. 538 config : RegistrationConfigAdvanced,
  539. 539) -> RegistrationResultAdvanced {
  540. 540● if config.algorithm == RegistrationAlgorithm::PhaseCorrelation {
  541. 541● phase_correlation_registration(img1, img2)
  542. 542○ } else if config.algorithm == RegistrationAlgorithm::FeatureBased {
  543. 543○ feature_based_registration(img1, img2, config)
  544. 544 } else {
  545. 545○ phase_correlation_registration(img1, img2)
  546. 546 }
  547. 547}
  548. 548
  549. 549///|
  550. 550/// 生成配准报告
  551. 551pub fn registration_report_to_string_advanced(
  552. 552 result : RegistrationResultAdvanced,
  553. 553) -> String {
  554. 554● let mut report = "## 高级图像配准报告\n\n"
  555. 555 report = report + "### 配准信息\n\n"
  556. 556 report = report + "| 指标 | 值 |\n|------|------|\n"
  557. 557 report = report +
  558. 558 "| 算法 | " +
  559. 559 (if result.algorithm == RegistrationAlgorithm::PhaseCorrelation {
  560. 560● "相位相关"
  561. 561● } else if result.algorithm == RegistrationAlgorithm::FeatureBased {
  562. 562● "基于特征"
  563. 563● } else if result.algorithm == RegistrationAlgorithm::IntensityBased {
  564. 564● "基于强度"
  565. 565● } else if result.algorithm == RegistrationAlgorithm::MutualInformation {
  566. 566● "互信息"
  567. 567● } else if result.algorithm ==
  568. 568 RegistrationAlgorithm::NormalizedCrossCorrelation {
  569. 569● "归一化互相关"
  570. 570 } else {
  571. 571○ "未知"
  572. 572 }) +
  573. 573 " |\n"
  574. 574 report = report +
  575. 575 "| 变换类型 | " +
  576. 576 (if result.transform_type == TransformType::Translation {
  577. 577● "平移"
  578. 578● } else if result.transform_type == TransformType::Rigid {
  579. 579● "刚性"
  580. 580● } else if result.transform_type == TransformType::Similarity {
  581. 581● "相似"
  582. 582● } else if result.transform_type == TransformType::Affine {
  583. 583● "仿射"
  584. 584● } else if result.transform_type == TransformType::Perspective {
  585. 585● "透视"
  586. 586 } else {
  587. 587● "未知"
  588. 588 }) +
  589. 589 " |\n"
  590. 590 report = report +
  591. 591 "| 平移 X | " +
  592. 592● result.translation_x.to_string() +
  593. 593 " 像素 |\n"
  594. 594 report = report +
  595. 595 "| 平移 Y | " +
  596. 596● result.translation_y.to_string() +
  597. 597 " 像素 |\n"
  598. 598 report = report +
  599. 599 "| 旋转角度 | " +
  600. 600● result.rotation_angle.to_string() +
  601. 601 " 度 |\n"
  602. 602● report = report + "| 缩放 X | " + result.scale_x.to_string() + " |\n"
  603. 603● report = report + "| 缩放 Y | " + result.scale_y.to_string() + " |\n"
  604. 604 report = report +
  605. 605 "| 相关系数 | " +
  606. 606● result.correlation.to_string() +
  607. 607 " |\n"
  608. 608 report = report +
  609. 609 "| 互信息 | " +
  610. 610● result.mutual_information.to_string() +
  611. 611 " |\n"
  612. 612● report = report + "| RMSE | " + result.rmse.to_string() + " |\n"
  613. 613 report = report +
  614. 614 "| 特征点数 | " +
  615. 615● result.num_feature_points.to_string() +
  616. 616 " |\n"
  617. 617● report = report + "| 内点数 | " + result.num_inliers.to_string() + " |\n"
  618. 618
  619. 619 report
  620. 620}