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