image.process\feature\sift.mbt
91.5% · 204 / 223 points · 587 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # SIFT 特征 sift - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// SIFT 特征检测(纯 MoonBit) - 7
// Scale-Invariant Feature Transform - 8
// Lowe, "Distinctive Image Features from Scale-Invariant Keypoints" (2004) - 9
- 10
///| - 11
/// SIFT 关键点 - 12
pub(all) struct SiftKeyPoint { - 13
x : Float - 14
y : Float - 15
octave : Int32 - 16
layer : Int32 - 17
sigma : Float - 18
response : Float - 19
angle : Float - 20
} - 21
- 22
///| - 23
/// SIFT 描述子(128 维) - 24
pub(all) struct SiftDescriptor { - 25
kp : SiftKeyPoint - 26
data : Array[Float] // 128 维浮点描述子 - 27
} - 28
- 29
///| - 30
/// SIFT 特征检测。 - 31
/// 检测尺度不变关键点并计算 128 维描述子。 - 32
/// max_features 控制最大特征数,contrast_threshold 为对比度阈值。 - 33
pub fn sift_detect( - 34
img : @types.Image, - 35
max_features~ : Int32 = 500, - 36
contrast_threshold~ : Float = 0.04F, - 37
) -> Array[SiftDescriptor] raise @types.LoadError { - 38
// 输入验证 - 39●
if img.width <= 0 || img.height <= 0 { - 40○
raise @types.LoadError::DecodeFailed( - 41
"sift_detect: 图像尺寸必须大于0", - 42
) - 43
} - 44
if img.width < 16 || img.height < 16 { - 45●
raise @types.LoadError::DecodeFailed( - 46
"sift_detect: SIFT 需要至少 16x16 图像", - 47
) - 48
} - 49
if img.channels < 1 || img.channels > 4 { - 50○
raise @types.LoadError::DecodeFailed( - 51
"sift_detect: 通道数必须在1-4之间", - 52
) - 53
} - 54
let expected_size = img.width * img.height * img.channels - 55●
if img.data.length() != expected_size { - 56○
raise @types.LoadError::DecodeFailed( - 57
"sift_detect: 数据大小不匹配,期望 " + - 58○
expected_size.to_string() + - 59
",实际 " + - 60○
img.data.length().to_string(), - 61
) - 62
} - 63
if max_features <= 0 { - 64○
raise @types.LoadError::DecodeFailed( - 65
"sift_detect: max_features必须大于0", - 66
) - 67
} - 68
if contrast_threshold <= 0.0F { - 69○
raise @types.LoadError::DecodeFailed( - 70
"sift_detect: contrast_threshold必须大于0", - 71
) - 72
} - 73●
let (gray, w, h) = to_gray_sift(img) - 74
let n_layers = 3 - 75
let sigma0 = 1.6F - 76
let edge_thresh = 10.0F - 77
// 构建高斯金字塔: 每个元素为 (levels, w, h) - 78●
let gauss_pyramid = build_gaussian_pyramid_sift(gray, w, h, n_layers, sigma0) - 79
// 构建 DoG 金字塔 - 80●
let dog_pyramid = build_dog_pyramid(gauss_pyramid) - 81
// 检测关键点 - 82
let keypoints : Array[SiftKeyPoint] = [] - 83●
for oct in 0..<gauss_pyramid.length() { - 84●
let (gauss_levels, oct_w, oct_h) = gauss_pyramid[oct] - 85
let (dog_levels, _, _) = dog_pyramid[oct] - 86
// dog_levels 有 n_levels-1 层,在 1..<(n_levels-2) 检测 - 87●
for layer in 1..<(dog_levels.length() - 1) { - 88●
let prev_dog = dog_levels[layer - 1] - 89
let curr_dog = dog_levels[layer] - 90
let next_dog = dog_levels[layer + 1] - 91
let sigma = sigma0 * - 92●
Float::from_int(1 << oct) * - 93●
Float::from_double( - 94●
@math.pow( - 95
2.0, - 96●
Float::from_int(layer).to_double() / - 97●
Float::from_int(n_layers).to_double(), - 98
), - 99
) - 100
for y in 1..<(oct_h - 1) { - 101●
for x in 1..<(oct_w - 1) { - 102●
let val = curr_dog[y * oct_w + x] - 103
// 检查是否为 3x3x3 局部极值 - 104●
if !is_extremum(prev_dog, curr_dog, next_dog, x, y, oct_w) { - 105●
continue - 106
} - 107
// 对比度过滤 - 108●
if val.abs() < contrast_threshold * 0.5F { - 109○
continue - 110
} - 111
// 边缘响应过滤 - 112●
let ratio = edge_response(curr_dog, x, y, oct_w) - 113
if ratio > edge_thresh { - 114●
continue - 115
} - 116●
let fx = Float::from_int(x) - 117●
let fy = Float::from_int(y) - 118
// 方向分配 - 119
let base_gray = gauss_levels[layer] - 120●
let angles = compute_orientation_sift( - 121
base_gray, oct_w, oct_h, fx, fy, sigma, - 122
) - 123
for angle in angles { - 124●
keypoints.push(SiftKeyPoint::{ - 125●
x: fx * Float::from_int(1 << oct), - 126●
y: fy * Float::from_int(1 << oct), - 127
octave: oct, - 128
layer, - 129
sigma, - 130
response: val, - 131
angle, - 132
}) - 133
} - 134
} - 135
} - 136
} - 137
} - 138
// 限制特征数 - 139●
let kps = if keypoints.length() > max_features { - 140●
keypoints[0:max_features] - 141
} else { - 142●
keypoints - 143
} - 144
// 计算描述子 - 145
let descriptors : Array[SiftDescriptor] = [] - 146
for kp in kps { - 147●
let (gauss_levels, oct_w, oct_h) = gauss_pyramid[kp.octave] - 148●
let scale = Float::from_int(1 << kp.octave) - 149
let local_x = kp.x / scale - 150
let local_y = kp.y / scale - 151
let level_gray = gauss_levels[kp.layer] - 152●
let desc = compute_sift_descriptor( - 153
level_gray, - 154
oct_w, - 155
oct_h, - 156
local_x, - 157
local_y, - 158
kp.angle, - 159
kp.sigma, - 160
) - 161●
descriptors.push(SiftDescriptor::{ kp, data: desc, }) - 162
} - 163
descriptors - 164
} - 165
- 166
// ==================== 高斯金字塔 ==================== - 167
- 168
///| - 169
fn build_gaussian_pyramid_sift( - 170
gray : Array[Float], - 171
w : Int32, - 172
h : Int32, - 173
n_layers : Int32, - 174
sigma0 : Float, - 175
) -> Array[(Array[Array[Float]], Int32, Int32)] { - 176●
let n_levels = n_layers + 3 - 177●
let n_octaves = compute_n_octaves(w, h) - 178
let pyramid : Array[(Array[Array[Float]], Int32, Int32)] = [] - 179
let mut cur_gray = gray - 180
let mut cur_w = w - 181
let mut cur_h = h - 182
for oct in 0..<n_octaves { - 183●
let levels : Array[Array[Float]] = [] - 184
// 第一层:octave 0 需要模糊 sigma0,后续 octave 直接用下采样图 - 185
let first = if oct == 0 { - 186●
gaussian_blur_float(cur_gray, cur_w, cur_h, sigma0) - 187
} else { - 188●
cur_gray.copy() - 189
} - 190●
levels.push(first) - 191
// 后续层:逐层增量模糊 - 192
for i in 1..<n_levels { - 193●
let target_sigma = sigma0 * - 194●
Float::from_double( - 195●
@math.pow( - 196
2.0, - 197●
Float::from_int(i).to_double() / - 198●
Float::from_int(n_layers).to_double(), - 199
), - 200
) - 201
let prev_sigma = sigma0 * - 202●
Float::from_double( - 203●
@math.pow( - 204
2.0, - 205●
Float::from_int(i - 1).to_double() / - 206●
Float::from_int(n_layers).to_double(), - 207
), - 208
) - 209
let delta_sq = target_sigma * target_sigma - prev_sigma * prev_sigma - 210◐
let delta_sigma = if delta_sq > 0.0F { delta_sq.sqrt() } else { 0.0F } - 211●
let blurred = gaussian_blur_float( - 212
levels[i - 1], - 213
cur_w, - 214
cur_h, - 215
delta_sigma, - 216
) - 217●
levels.push(blurred) - 218
} - 219●
pyramid.push((levels, cur_w, cur_h)) - 220
// 下采样为下一 octave 准备 - 221
if oct < n_octaves - 1 { - 222●
let down_idx = n_layers - 223●
let (down_gray, down_w, down_h) = downsample( - 224
levels[down_idx], - 225
cur_w, - 226
cur_h, - 227
) - 228
cur_gray = down_gray - 229
cur_w = down_w - 230
cur_h = down_h - 231
} - 232
} - 233
pyramid - 234
} - 235
- 236
///| - 237
fn compute_n_octaves(w : Int32, h : Int32) -> Int32 { - 238◐
let min_dim = if w < h { w } else { h } - 239
let mut n = 0 - 240
let mut d = min_dim - 241
while d >= 16 { - 242●
n += 1 - 243
d = d / 2 - 244
} - 245
if n < 1 { - 246○
1 - 247
} else { - 248●
n - 249
} - 250
} - 251
- 252
///| - 253
fn build_dog_pyramid( - 254
pyramid : Array[(Array[Array[Float]], Int32, Int32)], - 255
) -> Array[(Array[Array[Float]], Int32, Int32)] { - 256●
let result : Array[(Array[Array[Float]], Int32, Int32)] = [] - 257●
for oct in 0..<pyramid.length() { - 258●
let (levels, w, h) = pyramid[oct] - 259
let dog_levels : Array[Array[Float]] = [] - 260●
for i in 1..<levels.length() { - 261●
let diff : Array[Float] = Array::make(w * h, 0.0F) - 262
for j in 0..<(w * h) { - 263●
diff[j] = levels[i][j] - levels[i - 1][j] - 264
} - 265●
dog_levels.push(diff) - 266
} - 267●
result.push((dog_levels, w, h)) - 268
} - 269
result - 270
} - 271
- 272
// ==================== 关键点检测 ==================== - 273
- 274
///| - 275
fn is_extremum( - 276
prev_dog : Array[Float], - 277
curr_dog : Array[Float], - 278
next_dog : Array[Float], - 279
x : Int32, - 280
y : Int32, - 281
w : Int32, - 282
) -> Bool { - 283●
let val = curr_dog[y * w + x] - 284
let is_max = val > 0.0F - 285
for dy in -1..<=1 { - 286●
for dx in -1..<=1 { - 287●
let idx = (y + dy) * w + (x + dx) - 288
if is_max { - 289●
if !(dx == 0 && dy == 0) && curr_dog[idx] >= val { - 290●
return false - 291
} - 292
if prev_dog[idx] >= val { - 293●
return false - 294
} - 295
if next_dog[idx] >= val { - 296●
return false - 297
} - 298
} else { - 299●
if !(dx == 0 && dy == 0) && curr_dog[idx] <= val { - 300●
return false - 301
} - 302
if prev_dog[idx] <= val { - 303●
return false - 304
} - 305
if next_dog[idx] <= val { - 306●
return false - 307
} - 308
} - 309
} - 310
} - 311
true - 312
} - 313
- 314
///| - 315
fn edge_response(dog : Array[Float], x : Int32, y : Int32, w : Int32) -> Float { - 316●
let dxx = dog[y * w + x + 1] - 2.0F * dog[y * w + x] + dog[y * w + x - 1] - 317
let dyy = dog[(y + 1) * w + x] - 2.0F * dog[y * w + x] + dog[(y - 1) * w + x] - 318
let dxy = ( - 319
dog[(y + 1) * w + x + 1] - - 320
dog[(y + 1) * w + x - 1] - - 321
dog[(y - 1) * w + x + 1] + - 322
dog[(y - 1) * w + x - 1] - 323
) / - 324
4.0F - 325
let trace = dxx + dyy - 326
let det = dxx * dyy - dxy * dxy - 327
if det <= 0.0F { - 328○
return 100.0F - 329
} - 330
trace * trace / det - 331
} - 332
- 333
///| - 334
fn compute_orientation_sift( - 335
gray : Array[Float], - 336
w : Int32, - 337
h : Int32, - 338
cx : Float, - 339
cy : Float, - 340
sigma : Float, - 341
) -> Array[Float] { - 342●
let n_bins = 36 - 343●
let hist : Array[Float] = Array::make(n_bins, 0.0F) - 344●
let radius = (sigma * 3.0F).to_int() - 345●
let ix = cx.to_int() - 346●
let iy = cy.to_int() - 347
let two_pi = 2.0F * 3.14159265F - 348
for dy in -radius..<=radius { - 349●
let y = iy + dy - 350
if y < 1 || y >= h - 1 { - 351●
continue - 352
} - 353
for dx in -radius..<=radius { - 354●
let x = ix + dx - 355
if x < 1 || x >= w - 1 { - 356●
continue - 357
} - 358
let gx = gray[y * w + x + 1] - gray[y * w + x - 1] - 359
let gy = gray[(y + 1) * w + x] - gray[(y - 1) * w + x] - 360●
let mag = (gx * gx + gy * gy).sqrt() - 361●
let angle = Float::from_double( - 362●
@math.atan2(gy.to_double(), gx.to_double()), - 363
) - 364●
let norm_angle = if angle < 0.0F { angle + two_pi } else { angle } - 365●
let bin = (norm_angle / two_pi * Float::from_int(n_bins)).to_int() % - 366
n_bins - 367●
let weight = Float::from_double( - 368●
@math.exp( - 369●
-Float::from_int(dx * dx + dy * dy).to_double() / - 370●
(2.0F * sigma * sigma).to_double(), - 371
), - 372
) - 373
hist[bin] += weight * mag - 374
} - 375
} - 376
// 找峰值 - 377
let angles : Array[Float] = [] - 378
let mut max_val = 0.0F - 379
let mut max_bin = 0 - 380
for i in 0..<n_bins { - 381●
if hist[i] > max_val { - 382●
max_val = hist[i] - 383
max_bin = i - 384
} - 385
} - 386
if max_val > 0.0F { - 387●
let angle = Float::from_int(max_bin) * two_pi / Float::from_int(n_bins) - 388●
angles.push(angle) - 389
// 检查 80% 峰值 - 390
for i in 0..<n_bins { - 391●
if i != max_bin && hist[i] > 0.8F * max_val { - 392●
let a = Float::from_int(i) * two_pi / Float::from_int(n_bins) - 393●
angles.push(a) - 394
} - 395
} - 396
} - 397
angles - 398
} - 399
- 400
// ==================== 描述子 ==================== - 401
- 402
///| - 403
fn compute_sift_descriptor( - 404
gray : Array[Float], - 405
w : Int32, - 406
h : Int32, - 407
cx : Float, - 408
cy : Float, - 409
angle : Float, - 410
sigma : Float, - 411
) -> Array[Float] { - 412●
let desc : Array[Float] = Array::make(128, 0.0F) - 413●
let radius = (sigma * 4.0F).to_int() - 414●
let cos_a = Float::from_double(@math.cos(angle.to_double())) - 415●
let sin_a = Float::from_double(@math.sin(angle.to_double())) - 416●
let ix = cx.to_int() - 417●
let iy = cy.to_int() - 418
let two_pi = 2.0F * 3.14159265F - 419
for dy in -radius..<=radius { - 420●
let y = iy + dy - 421
if y < 1 || y >= h - 1 { - 422●
continue - 423
} - 424
for dx in -radius..<=radius { - 425●
let x = ix + dx - 426
if x < 1 || x >= w - 1 { - 427●
continue - 428
} - 429
// 旋转到关键点坐标系 - 430●
let rx = Float::from_int(dx) * cos_a + Float::from_int(dy) * sin_a - 431●
let ry = -Float::from_int(dx) * sin_a + Float::from_int(dy) * cos_a - 432
// 分配到 4x4 cell - 433●
let cell_x = (rx / (sigma * 2.0F) + 2.0F).to_int() - 434●
let cell_y = (ry / (sigma * 2.0F) + 2.0F).to_int() - 435
if cell_x < 0 || cell_x >= 4 || cell_y < 0 || cell_y >= 4 { - 436●
continue - 437
} - 438
// 梯度 - 439
let gx = gray[y * w + x + 1] - gray[y * w + x - 1] - 440
let gy = gray[(y + 1) * w + x] - gray[(y - 1) * w + x] - 441●
let mag = (gx * gx + gy * gy).sqrt() - 442●
let grad_angle = Float::from_double( - 443●
@math.atan2(gy.to_double(), gx.to_double()), - 444
) - - 445
angle - 446
let norm_angle = if grad_angle < 0.0F { - 447●
grad_angle + two_pi - 448
} else { - 449●
grad_angle - 450
} - 451●
let bin = (norm_angle / two_pi * 8.0F).to_int() % 8 - 452
// 高斯加权 - 453●
let weight = Float::from_double( - 454●
@math.exp( - 455●
-Float::from_int(dx * dx + dy * dy).to_double() / - 456●
(2.0F * sigma * sigma * 4.0F).to_double(), - 457
), - 458
) - 459
let idx = cell_y * 32 + cell_x * 8 + bin - 460
desc[idx] += weight * mag - 461
} - 462
} - 463
// 归一化 - 464
let mut norm = 0.0F - 465
for v in desc { - 466●
norm += v * v - 467
} - 468●
norm = norm.sqrt() - 469
if norm > 0.0F { - 470●
for i in 0..<128 { - 471●
desc[i] = desc[i] / norm - 472
if desc[i] > 0.2F { - 473●
desc[i] = 0.2F - 474
} - 475
} - 476
// 再次归一化 - 477
let mut norm2 = 0.0F - 478
for v in desc { - 479●
norm2 += v * v - 480
} - 481●
norm2 = norm2.sqrt() - 482
if norm2 > 0.0F { - 483●
for i in 0..<128 { - 484●
desc[i] = desc[i] / norm2 - 485
} - 486
} - 487
} - 488
desc - 489
} - 490
- 491
// ==================== 辅助函数 ==================== - 492
- 493
///| - 494
fn to_gray_sift(img : @types.Image) -> (Array[Float], Int32, Int32) { - 495●
let w = img.width - 496
let h = img.height - 497
let ch = img.channels - 498
let n = w * h - 499●
let gray : Array[Float] = Array::make(n, 0.0F) - 500
for i in 0..<n { - 501●
if ch >= 3 { - 502●
let r = img.data[i * ch].to_int() - 503●
let g = img.data[i * ch + 1].to_int() - 504●
let b = img.data[i * ch + 2].to_int() - 505●
gray[i] = Float::from_int((r * 299 + g * 587 + b * 114) / 1000) / 255.0F - 506
} else { - 507●
gray[i] = Float::from_int(img.data[i * ch].to_int()) / 255.0F - 508
} - 509
} - 510
(gray, w, h) - 511
} - 512
- 513
///| - 514
fn gaussian_blur_float( - 515
gray : Array[Float], - 516
w : Int32, - 517
h : Int32, - 518
sigma : Float, - 519
) -> Array[Float] { - 520●
if sigma < 0.1F { - 521○
return gray.copy() - 522
} - 523●
let radius = (sigma * 3.0F).to_int() - 524
if radius < 1 { - 525○
return gray.copy() - 526
} - 527
// 可分离高斯:先水平后垂直 - 528●
let kernel : Array[Float] = Array::make(2 * radius + 1, 0.0F) - 529
let mut sum = 0.0F - 530
for i in -radius..<=radius { - 531●
let v = Float::from_double( - 532●
@math.exp( - 533●
-Float::from_int(i * i).to_double() / (2.0F * sigma * sigma).to_double(), - 534
), - 535
) - 536
kernel[i + radius] = v - 537
sum += v - 538
} - 539●
for i in 0..<kernel.length() { - 540●
kernel[i] = kernel[i] / sum - 541
} - 542
// 水平模糊 - 543●
let temp : Array[Float] = Array::make(w * h, 0.0F) - 544
for y in 0..<h { - 545●
for x in 0..<w { - 546●
let mut acc = 0.0F - 547
for k in -radius..<=radius { - 548●
let sx = (x + k).clamp(min=0, max=w - 1) - 549
acc += kernel[k + radius] * gray[y * w + sx] - 550
} - 551
temp[y * w + x] = acc - 552
} - 553
} - 554
// 垂直模糊 - 555●
let out : Array[Float] = Array::make(w * h, 0.0F) - 556
for y in 0..<h { - 557●
for x in 0..<w { - 558●
let mut acc = 0.0F - 559
for k in -radius..<=radius { - 560●
let sy = (y + k).clamp(min=0, max=h - 1) - 561
acc += kernel[k + radius] * temp[sy * w + x] - 562
} - 563
out[y * w + x] = acc - 564
} - 565
} - 566
out - 567
} - 568
- 569
///| - 570
fn downsample( - 571
gray : Array[Float], - 572
w : Int32, - 573
h : Int32, - 574
) -> (Array[Float], Int32, Int32) { - 575●
let nw = w / 2 - 576
let nh = h / 2 - 577
if nw < 1 || nh < 1 { - 578○
return (gray.copy(), w, h) - 579
} - 580●
let out : Array[Float] = Array::make(nw * nh, 0.0F) - 581
for y in 0..<nh { - 582●
for x in 0..<nw { - 583●
out[y * nw + x] = gray[y * 2 * w + x * 2] - 584
} - 585
} - 586
(out, nw, nh) - 587
}