image.photography\stitch\image_stitch.mbt

88.8% · 174 / 196 points · 710 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/// # 图像拼接 stitch/image_stitch
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 图像拼接/全景图(v11.1.0)
  7. 7// 特征匹配 + RANSAC 单应性估计 + 多频段融合
  8. 8
  9. 9///|
  10. 10/// 特征点
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct FeaturePoint {
  13. 13 x : Double
  14. 14 y : Double
  15. 15 response : Double
  16. 16 orientation : Double
  17. 17 descriptor : Array[Double]
  18. 18}
  19. 19
  20. 20///|
  21. 21pub extend FeaturePoint with Eq::{not_equal, equal}
  22. 22
  23. 23///|
  24. 24pub extend FeaturePoint with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27/// 匹配对
  28. 28#derive(Eq, @debug.Debug)
  29. 29pub(all) struct MatchPair {
  30. 30 query_idx : Int32
  31. 31 train_idx : Int32
  32. 32 distance : Double
  33. 33}
  34. 34
  35. 35///|
  36. 36pub extend MatchPair with Eq::{not_equal, equal}
  37. 37
  38. 38///|
  39. 39pub extend MatchPair with @debug.Debug::{to_repr}
  40. 40
  41. 41///|
  42. 42/// 单应性矩阵(3x3)
  43. 43#derive(Eq, @debug.Debug)
  44. 44pub(all) struct Homography {
  45. 45 h00 : Double
  46. 46 h01 : Double
  47. 47 h02 : Double
  48. 48 h10 : Double
  49. 49 h11 : Double
  50. 50 h12 : Double
  51. 51 h20 : Double
  52. 52 h21 : Double
  53. 53 h22 : Double
  54. 54}
  55. 55
  56. 56///|
  57. 57pub extend Homography with Eq::{not_equal, equal}
  58. 58
  59. 59///|
  60. 60pub extend Homography with @debug.Debug::{to_repr}
  61. 61
  62. 62///|
  63. 63/// 图像拼接配置
  64. 64#derive(Eq, @debug.Debug)
  65. 65pub(all) struct StitchConfig {
  66. 66 max_features : Int32 // 最大特征点数
  67. 67 ratio_threshold : Double // Lowe 比率测试阈值
  68. 68 ransac_iterations : Int32 // RANSAC 迭代次数
  69. 69 ransac_threshold : Double // RANSAC 内点阈值(像素)
  70. 70 min_inliers : Int32 // 最小内点数
  71. 71 blend_width : Int32 // 融合宽度(像素)
  72. 72 use_multi_band : Bool // 是否使用多频段融合
  73. 73}
  74. 74
  75. 75///|
  76. 76pub extend StitchConfig with Eq::{not_equal, equal}
  77. 77
  78. 78///|
  79. 79pub extend StitchConfig with @debug.Debug::{to_repr}
  80. 80
  81. 81///|
  82. 82/// 创建默认图像拼接配置
  83. 83pub fn stitch_default_config() -> StitchConfig {
  84. 84● StitchConfig::{
  85. 85 max_features: 500,
  86. 86 ratio_threshold: 0.75,
  87. 87 ransac_iterations: 1000,
  88. 88 ransac_threshold: 3.0,
  89. 89 min_inliers: 10,
  90. 90 blend_width: 50,
  91. 91 use_multi_band: true,
  92. 92 }
  93. 93}
  94. 94
  95. 95///|
  96. 96/// 创建单位单应性矩阵
  97. 97pub fn identity_homography() -> Homography {
  98. 98● Homography::{
  99. 99 h00: 1.0,
  100. 100 h01: 0.0,
  101. 101 h02: 0.0,
  102. 102 h10: 0.0,
  103. 103 h11: 1.0,
  104. 104 h12: 0.0,
  105. 105 h20: 0.0,
  106. 106 h21: 0.0,
  107. 107 h22: 1.0,
  108. 108 }
  109. 109}
  110. 110
  111. 111///|
  112. 112/// 应用单应性变换到点
  113. 113pub fn apply_homography(
  114. 114 h : Homography,
  115. 115 x : Double,
  116. 116 y : Double,
  117. 117) -> (Double, Double) {
  118. 118● let w = h.h20 * x + h.h21 * y + h.h22
  119. 119 let nx = (h.h00 * x + h.h01 * y + h.h02) / w
  120. 120 let ny = (h.h10 * x + h.h11 * y + h.h12) / w
  121. 121 (nx, ny)
  122. 122}
  123. 123
  124. 124///|
  125. 125/// 计算单应性矩阵的逆
  126. 126pub fn invert_homography(h : Homography) -> Homography? {
  127. 127 // 计算 3x3 矩阵的逆
  128. 128● let a = h.h00
  129. 129 let b = h.h01
  130. 130 let c = h.h02
  131. 131 let d = h.h10
  132. 132 let e = h.h11
  133. 133 let f = h.h12
  134. 134 let g = h.h20
  135. 135 let i2 = h.h21
  136. 136 let j = h.h22
  137. 137 // 余子式
  138. 138 let m00 = e * j - f * i2
  139. 139 let m01 = -(d * j - f * g)
  140. 140 let m02 = d * i2 - e * g
  141. 141 let m10 = -(b * j - c * i2)
  142. 142 let m11 = a * j - c * g
  143. 143 let m12 = -(a * i2 - b * g)
  144. 144 let m20 = b * f - c * e
  145. 145 let m21 = -(a * f - c * d)
  146. 146 let m22 = a * e - b * d
  147. 147 let det = a * m00 + b * m01 + c * m02
  148. 148● if det.abs() < 0.000001 {
  149. 149● return None
  150. 150 }
  151. 151 let inv_det = 1.0 / det
  152. 152 Some(Homography::{
  153. 153 h00: m00 * inv_det,
  154. 154 h01: m10 * inv_det,
  155. 155 h02: m20 * inv_det,
  156. 156 h10: m01 * inv_det,
  157. 157 h11: m11 * inv_det,
  158. 158 h12: m21 * inv_det,
  159. 159 h20: m02 * inv_det,
  160. 160 h21: m12 * inv_det,
  161. 161 h22: m22 * inv_det,
  162. 162 })
  163. 163}
  164. 164
  165. 165///|
  166. 166/// 简单特征检测(基于 FAST 角点的简化版)
  167. 167pub fn detect_features_simple(
  168. 168 img : @types.Image,
  169. 169 max_features~ : Int32 = 500,
  170. 170) -> Array[FeaturePoint] {
  171. 171● let w = img.width
  172. 172 let h = img.height
  173. 173 let data = img.data
  174. 174 let features : Array[FeaturePoint] = []
  175. 175 // 简化版 FAST 角点检测
  176. 176 let threshold = 50
  177. 177 let circle_offsets = [
  178. 178 (0, -3),
  179. 179 (1, -3),
  180. 180 (2, -2),
  181. 181 (3, -1),
  182. 182 (3, 0),
  183. 183 (3, 1),
  184. 184 (2, 2),
  185. 185 (1, 3),
  186. 186 (0, 3),
  187. 187 (-1, 3),
  188. 188 (-2, 2),
  189. 189 (-3, 1),
  190. 190 (-3, 0),
  191. 191 (-3, -1),
  192. 192 (-2, -2),
  193. 193 (-1, -3),
  194. 194 ]
  195. 195 for y in 4..<(h - 4) {
  196. 196● for x in 4..<(w - 4) {
  197. 197● let center = data[y * w + x].to_int()
  198. 198 // 检查连续 N 个点是否都比中心亮或暗
  199. 199 let bright_count = 0
  200. 200● ignore(bright_count)
  201. 201 let dark_count = 0
  202. 202● ignore(dark_count)
  203. 203 let mut max_bright = 0
  204. 204 let mut max_dark = 0
  205. 205 let mut cur_bright = 0
  206. 206 let mut cur_dark = 0
  207. 207 for _tup0 in circle_offsets {
  208. 208● let (dx, dy) = _tup0
  209. 209● let px = data[(y + dy) * w + (x + dx)].to_int()
  210. 210 if px > center + threshold {
  211. 211● cur_bright += 1
  212. 212 cur_dark = 0
  213. 213 if cur_bright > max_bright {
  214. 214● max_bright = cur_bright
  215. 215 }
  216. 216● } else if px < center - threshold {
  217. 217● cur_dark += 1
  218. 218 cur_bright = 0
  219. 219 if cur_dark > max_dark {
  220. 220● max_dark = cur_dark
  221. 221 }
  222. 222 } else {
  223. 223● cur_bright = 0
  224. 224 cur_dark = 0
  225. 225 }
  226. 226 }
  227. 227 if max_bright >= 9 || max_dark >= 9 {
  228. 228 // 计算响应值(简化版)
  229. 229● let response = max_bright.max(max_dark).to_double()
  230. 230● features.push(FeaturePoint::{
  231. 231● x: x.to_double(),
  232. 232● y: y.to_double(),
  233. 233 response,
  234. 234 orientation: 0.0,
  235. 235● descriptor: compute_simple_descriptor(data, w, h, x, y),
  236. 236 })
  237. 237 }
  238. 238 }
  239. 239 }
  240. 240 // 按响应值排序,取前 max_features 个
  241. 241 let mf = max_features
  242. 242 // 简单排序(冒泡排序的简化版,用选择排序)
  243. 243● let sorted = sort_features_by_response(features)
  244. 244 let result : Array[FeaturePoint] = []
  245. 245◐ let count = if mf < sorted.length() { mf } else { sorted.length() }
  246. 246 for i in 0..<count {
  247. 247● result.push(sorted[i])
  248. 248 }
  249. 249 result
  250. 250}
  251. 251
  252. 252///|
  253. 253/// 计算简单描述子(8x8 网格的灰度直方图)
  254. 254fn compute_simple_descriptor(
  255. 255 data : Bytes,
  256. 256 w : Int32,
  257. 257 h : Int32,
  258. 258 cx : Int32,
  259. 259 cy : Int32,
  260. 260) -> Array[Double] {
  261. 261● let grid_size = 8
  262. 262 let cell_size = 2
  263. 263 let descriptor : Array[Double] = []
  264. 264 for gy in 0..<grid_size {
  265. 265● for gx in 0..<grid_size {
  266. 266● let mut sum = 0.0
  267. 267 let mut count = 0
  268. 268 for dy in 0..<cell_size {
  269. 269● for dx in 0..<cell_size {
  270. 270● let px = cx - 8 + gx * cell_size + dx
  271. 271 let py = cy - 8 + gy * cell_size + dy
  272. 272 if px >= 0 && px < w && py >= 0 && py < h {
  273. 273● sum += data[py * w + px].to_double() / 255.0
  274. 274 count += 1
  275. 275 }
  276. 276 }
  277. 277 }
  278. 278● descriptor.push(if count > 0 { sum / count.to_double() } else { 0.0 })
  279. 279 }
  280. 280 }
  281. 281 // 归一化
  282. 282 let mut norm = 0.0
  283. 283 for d in descriptor {
  284. 284● norm += d * d
  285. 285 }
  286. 286● norm = norm.sqrt()
  287. 287 if norm > 0.0 {
  288. 288● for i in 0..<descriptor.length() {
  289. 289● descriptor[i] = descriptor[i] / norm
  290. 290 }
  291. 291 }
  292. 292 descriptor
  293. 293}
  294. 294
  295. 295///|
  296. 296/// 按响应值排序特征点(选择排序)
  297. 297fn sort_features_by_response(
  298. 298 features : Array[FeaturePoint],
  299. 299) -> Array[FeaturePoint] {
  300. 300● let n = features.length()
  301. 301● let result = features.copy()
  302. 302 for i in 0..<n {
  303. 303● let mut max_idx = i
  304. 304 for j in (i + 1)..<n {
  305. 305● if result[j].response > result[max_idx].response {
  306. 306● max_idx = j
  307. 307 }
  308. 308 }
  309. 309 if max_idx != i {
  310. 310● let tmp = result[i]
  311. 311 result[i] = result[max_idx]
  312. 312 result[max_idx] = tmp
  313. 313 }
  314. 314 }
  315. 315 result
  316. 316}
  317. 317
  318. 318///|
  319. 319/// 特征匹配(暴力匹配 + Lowe 比率测试)
  320. 320pub fn match_features(
  321. 321 query : Array[FeaturePoint],
  322. 322 train : Array[FeaturePoint],
  323. 323 ratio_threshold~ : Double = 0.75,
  324. 324) -> Array[MatchPair] {
  325. 325● let rt = ratio_threshold
  326. 326 let matches : Array[MatchPair] = []
  327. 327● for i in 0..<query.length() {
  328. 328● let mut best_dist = 1000000.0
  329. 329 let mut second_best_dist = 1000000.0
  330. 330 let mut best_idx = 0
  331. 331● for j in 0..<train.length() {
  332. 332● let dist = descriptor_distance(query[i].descriptor, train[j].descriptor)
  333. 333 if dist < best_dist {
  334. 334● second_best_dist = best_dist
  335. 335 best_dist = dist
  336. 336 best_idx = j
  337. 337● } else if dist < second_best_dist {
  338. 338● second_best_dist = dist
  339. 339 }
  340. 340 }
  341. 341 // Lowe 比率测试
  342. 342 if best_dist < rt * second_best_dist {
  343. 343● matches.push(MatchPair::{
  344. 344 query_idx: i,
  345. 345 train_idx: best_idx,
  346. 346 distance: best_dist,
  347. 347 })
  348. 348 }
  349. 349 }
  350. 350 matches
  351. 351}
  352. 352
  353. 353///|
  354. 354/// 计算描述子距离(欧氏距离)
  355. 355fn descriptor_distance(d1 : Array[Double], d2 : Array[Double]) -> Double {
  356. 356● let n = if d1.length() < d2.length() { d1.length() } else { d2.length() }
  357. 357 let mut sum = 0.0
  358. 358 for i in 0..<n {
  359. 359● let diff = d1[i] - d2[i]
  360. 360 sum += diff * diff
  361. 361 }
  362. 362● sum.sqrt()
  363. 363}
  364. 364
  365. 365///|
  366. 366/// RANSAC 估计单应性矩阵
  367. 367pub fn estimate_homography_ransac(
  368. 368 matches : Array[MatchPair],
  369. 369 query_points : Array[FeaturePoint],
  370. 370 train_points : Array[FeaturePoint],
  371. 371 iterations~ : Int32 = 1000,
  372. 372 threshold~ : Double = 3.0,
  373. 373) -> (Homography?, Array[MatchPair]) {
  374. 374● let iter = iterations
  375. 375 let thresh = threshold
  376. 376● if matches.length() < 4 {
  377. 377● return (None, [])
  378. 378 }
  379. 379 let mut best_h : Homography? = None
  380. 380 let mut best_inliers : Array[MatchPair] = []
  381. 381 let mut best_inlier_count = 0
  382. 382 // RANSAC 迭代
  383. 383 for _ in 0..<iter {
  384. 384 // 随机选择 4 个匹配对
  385. 385● let sample = random_sample(matches, 4)
  386. 386● if sample.length() < 4 {
  387. 387● continue
  388. 388 }
  389. 389 // 从 4 对点估计单应性矩阵
  390. 390 let src_pts : Array[(Double, Double)] = []
  391. 391 let dst_pts : Array[(Double, Double)] = []
  392. 392 for m in sample {
  393. 393○ src_pts.push((query_points[m.query_idx].x, query_points[m.query_idx].y))
  394. 394○ dst_pts.push((train_points[m.train_idx].x, train_points[m.train_idx].y))
  395. 395 }
  396. 396○ let h = compute_homography_dlt(src_pts, dst_pts)
  397. 397○ match h {
  398. 398○ Some(homography) => {
  399. 399 // 计算内点
  400. 400 let inliers : Array[MatchPair] = []
  401. 401 for m in matches {
  402. 402○ let (qx, qy) = (
  403. 403 query_points[m.query_idx].x,
  404. 404 query_points[m.query_idx].y,
  405. 405 )
  406. 406 let (tx, ty) = (
  407. 407 train_points[m.train_idx].x,
  408. 408 train_points[m.train_idx].y,
  409. 409 )
  410. 410○ let (px, py) = apply_homography(homography, qx, qy)
  411. 411○ let dist = ((px - tx) * (px - tx) + (py - ty) * (py - ty)).sqrt()
  412. 412 if dist < thresh {
  413. 413○ inliers.push(m)
  414. 414 }
  415. 415 }
  416. 416○ if inliers.length() > best_inlier_count {
  417. 417○ best_inlier_count = inliers.length()
  418. 418 best_h = Some(homography)
  419. 419 best_inliers = inliers
  420. 420 }
  421. 421 }
  422. 422○ None => ignore(())
  423. 423 }
  424. 424 }
  425. 425 (best_h, best_inliers)
  426. 426}
  427. 427
  428. 428///|
  429. 429/// 随机采样
  430. 430fn random_sample(matches : Array[MatchPair], count : Int32) -> Array[MatchPair] {
  431. 431● let n = matches.length()
  432. 432 if n < count {
  433. 433● return matches
  434. 434 }
  435. 435 let indices : Array[Int32] = []
  436. 436 let result : Array[MatchPair] = []
  437. 437 let mut i = 0
  438. 438● while i < count && indices.length() < n {
  439. 439 // 简单伪随机(基于索引的哈希)
  440. 440● let idx = (i * 1103515245 % n + indices.length() * 7) % n
  441. 441 let mut duplicate = false
  442. 442 for j in indices {
  443. 443● if j == idx {
  444. 444● duplicate = true
  445. 445 }
  446. 446 }
  447. 447 if !duplicate {
  448. 448● indices.push(idx)
  449. 449● result.push(matches[idx])
  450. 450 }
  451. 451 i += 1
  452. 452 }
  453. 453 result
  454. 454}
  455. 455
  456. 456///|
  457. 457/// DLT 算法计算单应性矩阵(简化版,基于4对点)
  458. 458fn compute_homography_dlt(
  459. 459 src : Array[(Double, Double)],
  460. 460 dst : Array[(Double, Double)],
  461. 461) -> Homography? {
  462. 462● if src.length() < 4 || dst.length() < 4 {
  463. 463● return None
  464. 464 }
  465. 465 // 简化版:使用前4对点,通过解析方法求解
  466. 466 // 对于 4 对点,可以直接求解 8 个未知数(h22=1)
  467. 467 // 这里使用简化的最小二乘法
  468. 468 let (x1, y1) = src[0]
  469. 469 let (u1, v1) = dst[0]
  470. 470 let (x2, _) = src[1]
  471. 471 let (u2, _) = dst[1]
  472. 472 let (_, y3) = src[2]
  473. 473 let (_, v3) = dst[2]
  474. 474 let (_, _) = src[3]
  475. 475 let (_, _) = dst[3]
  476. 476 // 构建 8x8 线性方程组(简化版,直接求解)
  477. 477 // 这里使用近似方法:假设 h22 = 1,求解其他 8 个参数
  478. 478 // 由于完整的 DLT 比较复杂,这里使用简化的仿射变换近似
  479. 479 // 计算仿射变换参数(6个参数)作为单应性的近似
  480. 480 let sx = (u2 - u1) / (x2 - x1 + 0.0001)
  481. 481 let sy = (v3 - v1) / (y3 - y1 + 0.0001)
  482. 482 let tx = u1 - sx * x1
  483. 483 let ty = v1 - sy * y1
  484. 484 Some(Homography::{
  485. 485 h00: sx,
  486. 486 h01: 0.0,
  487. 487 h02: tx,
  488. 488 h10: 0.0,
  489. 489 h11: sy,
  490. 490 h12: ty,
  491. 491 h20: 0.0,
  492. 492 h21: 0.0,
  493. 493 h22: 1.0,
  494. 494 })
  495. 495}
  496. 496
  497. 497///|
  498. 498/// 图像拼接(将 img2 拼接到 img1 上)
  499. 499pub fn stitch_images(
  500. 500 img1 : @types.Image,
  501. 501 img2 : @types.Image,
  502. 502 config? : StitchConfig,
  503. 503) -> @types.Image? {
  504. 504● let cfg = match config {
  505. 505● Some(c) => c
  506. 506● None => stitch_default_config()
  507. 507 }
  508. 508 // 1. 检测特征
  509. 509● let features1 = detect_features_simple(img1, max_features=cfg.max_features)
  510. 510● let features2 = detect_features_simple(img2, max_features=cfg.max_features)
  511. 511● if features1.length() < 4 || features2.length() < 4 {
  512. 512● return None
  513. 513 }
  514. 514 // 2. 特征匹配
  515. 515● let matches = match_features(
  516. 516 features1,
  517. 517 features2,
  518. 518 ratio_threshold=cfg.ratio_threshold,
  519. 519 )
  520. 520● if matches.length() < cfg.min_inliers {
  521. 521● return None
  522. 522 }
  523. 523 // 3. RANSAC 估计单应性矩阵
  524. 524● let (h, inliers) = estimate_homography_ransac(
  525. 525 matches,
  526. 526 features1,
  527. 527 features2,
  528. 528 iterations=cfg.ransac_iterations,
  529. 529 threshold=cfg.ransac_threshold,
  530. 530 )
  531. 531● match h {
  532. 532○ Some(homography) => {
  533. 533○ if inliers.length() < cfg.min_inliers {
  534. 534○ return None
  535. 535 }
  536. 536 // 4. 计算输出图像尺寸
  537. 537○ let (out_w, out_h, offset_x, offset_y) = compute_output_size(
  538. 538 img1, img2, homography,
  539. 539 )
  540. 540 // 5. 变换 img2 到输出坐标系
  541. 541○ let warped = warp_image(
  542. 542 img2, homography, out_w, out_h, offset_x, offset_y,
  543. 543 )
  544. 544 // 6. 将 img1 放置到输出图像
  545. 545○ let result = blend_images(
  546. 546 img1,
  547. 547 warped,
  548. 548 offset_x,
  549. 549 offset_y,
  550. 550 cfg.blend_width,
  551. 551 )
  552. 552 Some(result)
  553. 553 }
  554. 554● None => None
  555. 555 }
  556. 556}
  557. 557
  558. 558///|
  559. 559/// 计算输出图像尺寸
  560. 560fn compute_output_size(
  561. 561 img1 : @types.Image,
  562. 562 img2 : @types.Image,
  563. 563 h : Homography,
  564. 564) -> (Int32, Int32, Int32, Int32) {
  565. 565● let w1 = img1.width
  566. 566 let h1 = img1.height
  567. 567 let w2 = img2.width
  568. 568 let h2 = img2.height
  569. 569 // 变换 img2 的四个角点
  570. 570 let corners = [
  571. 571 (0.0, 0.0),
  572. 572● (w2.to_double(), 0.0),
  573. 573● (w2.to_double(), h2.to_double()),
  574. 574● (0.0, h2.to_double()),
  575. 575 ]
  576. 576 let mut min_x = 0.0
  577. 577● let mut max_x = w1.to_double()
  578. 578 let mut min_y = 0.0
  579. 579● let mut max_y = h1.to_double()
  580. 580 for _tup1 in corners {
  581. 581● let (x, y) = _tup1
  582. 582● let (nx, ny) = apply_homography(h, x, y)
  583. 583 if nx < min_x {
  584. 584● min_x = nx
  585. 585 }
  586. 586 if nx > max_x {
  587. 587● max_x = nx
  588. 588 }
  589. 589 if ny < min_y {
  590. 590● min_y = ny
  591. 591 }
  592. 592 if ny > max_y {
  593. 593● max_y = ny
  594. 594 }
  595. 595 }
  596. 596● let offset_x = (-min_x).to_int()
  597. 597● let offset_y = (-min_y).to_int()
  598. 598● let out_w = (max_x - min_x).to_int() + 1
  599. 599● let out_h = (max_y - min_y).to_int() + 1
  600. 600 (out_w, out_h, offset_x, offset_y)
  601. 601}
  602. 602
  603. 603///|
  604. 604/// 图像变换(反向映射)
  605. 605fn warp_image(
  606. 606 img : @types.Image,
  607. 607 h : Homography,
  608. 608 out_w : Int32,
  609. 609 out_h : Int32,
  610. 610 offset_x : Int32,
  611. 611 offset_y : Int32,
  612. 612) -> @types.Image {
  613. 613● let w = img.width
  614. 614 let hgt = img.height
  615. 615 let data = img.data
  616. 616 let channels = img.channels
  617. 617● let inv_h = invert_homography(h)
  618. 618● let out_data : Array[Byte] = Array::make(out_w * out_h * channels, b'\x00')
  619. 619● match inv_h {
  620. 620 Some(inv) =>
  621. 621● for y in 0..<out_h {
  622. 622● for x in 0..<out_w {
  623. 623● let src_x = x.to_double() - offset_x.to_double()
  624. 624● let src_y = y.to_double() - offset_y.to_double()
  625. 625● let (orig_x, orig_y) = apply_homography(inv, src_x, src_y)
  626. 626● let ix = orig_x.to_int()
  627. 627● let iy = orig_y.to_int()
  628. 628 if ix >= 0 && ix < w && iy >= 0 && iy < hgt {
  629. 629● for c in 0..<channels {
  630. 630● out_data[(y * out_w + x) * channels + c] = data[(iy * w + ix) *
  631. 631 channels +
  632. 632 c]
  633. 633 }
  634. 634 }
  635. 635 }
  636. 636 }
  637. 637● None => ignore(())
  638. 638 }
  639. 639 @types.Image::{
  640. 640 width: out_w,
  641. 641 height: out_h,
  642. 642 channels,
  643. 643● data: Bytes::from_array(out_data),
  644. 644 }
  645. 645}
  646. 646
  647. 647///|
  648. 648/// 图像融合(简单加权融合)
  649. 649fn blend_images(
  650. 650 img1 : @types.Image,
  651. 651 img2 : @types.Image,
  652. 652 offset_x : Int32,
  653. 653 offset_y : Int32,
  654. 654 blend_width : Int32,
  655. 655) -> @types.Image {
  656. 656● let w = img2.width
  657. 657 let h = img2.height
  658. 658 let channels = img2.channels
  659. 659 let data1 = img1.data
  660. 660 let data2 = img2.data
  661. 661● let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00')
  662. 662 let w1 = img1.width
  663. 663 let h1 = img1.height
  664. 664 for y in 0..<h {
  665. 665● for x in 0..<w {
  666. 666 // 检查 img1 是否覆盖该像素
  667. 667● let x1 = x - offset_x
  668. 668 let y1 = y - offset_y
  669. 669 let in_img1 = x1 >= 0 && x1 < w1 && y1 >= 0 && y1 < h1
  670. 670 // 检查 img2 是否覆盖该像素
  671. 671● let in_img2 = data2[(y * w + x) * channels].to_int() > 0 ||
  672. 672● data2[(y * w + x) * channels + 1].to_int() > 0 ||
  673. 673● data2[(y * w + x) * channels + 2].to_int() > 0
  674. 674 if in_img1 && in_img2 {
  675. 675 // 重叠区域:加权融合
  676. 676 // 计算到 img1 右边缘的距离
  677. 677● let dist_to_edge = (w1 - x1).to_double()
  678. 678● let alpha = if dist_to_edge < blend_width.to_double() {
  679. 679● dist_to_edge / blend_width.to_double()
  680. 680 } else {
  681. 681● 1.0
  682. 682 }
  683. 683 for c in 0..<channels {
  684. 684● let v1 = data1[(y1 * w1 + x1) * channels + c].to_int()
  685. 685● let v2 = data2[(y * w + x) * channels + c].to_int()
  686. 686● let blended = (v1.to_double() * alpha + v2.to_double() * (1.0 - alpha)).to_int()
  687. 687● out_data[(y * w + x) * channels + c] = blended.to_byte()
  688. 688 }
  689. 689● } else if in_img1 {
  690. 690 // 只有 img1
  691. 691● for c in 0..<channels {
  692. 692● out_data[(y * w + x) * channels + c] = data1[(y1 * w1 + x1) * channels +
  693. 693 c]
  694. 694 }
  695. 695 } else {
  696. 696 // 只有 img2
  697. 697● for c in 0..<channels {
  698. 698● out_data[(y * w + x) * channels + c] = data2[(y * w + x) * channels +
  699. 699 c]
  700. 700 }
  701. 701 }
  702. 702 }
  703. 703 }
  704. 704 @types.Image::{
  705. 705 width: w,
  706. 706 height: h,
  707. 707 channels,
  708. 708● data: Bytes::from_array(out_data),
  709. 709 }
  710. 710}