image.process\feature\orb.mbt
91.5% · 107 / 117 points · 392 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # ORB 特征 orb - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// ORB 特征检测与描述(纯 MoonBit) - 7
// Oriented FAST and Rotated BRIEF - 8
// 参考: https://docs.opencv.org/4.x/d5/d3c/classcv_1_1Feature2D.html - 9
- 10
///| - 11
/// ORB 关键点:位置 + 响应 + 方向 - 12
pub(all) struct OrbKeyPoint { - 13
x : Int32 - 14
y : Int32 - 15
response : Float - 16
angle : Float // 方向角(弧度) - 17
} - 18
- 19
///| - 20
/// ORB 描述子:256 位二进制描述(32 个 Int) - 21
pub(all) struct OrbDescriptor { - 22
kp : OrbKeyPoint - 23
data : Array[Int32] // 32 个 Int,每个 32 位,共 256 位 - 24
} - 25
- 26
///| - 27
/// 特征匹配结果 - 28
pub(all) struct DescriptorMatch { - 29
query_idx : Int32 - 30
train_idx : Int32 - 31
distance : Int32 // 汉明距离 - 32
} - 33
- 34
// ==================== FAST 角点检测 ==================== - 35
- 36
///| - 37
/// FAST-9 圆周偏移(半径 3,16 个点) - 38
let fast_offsets : Array[(Int32, Int32)] = [ - 39
(0, -3), - 40
(1, -3), - 41
(2, -2), - 42
(3, -1), - 43
(3, 0), - 44
(3, 1), - 45
(2, 2), - 46
(1, 3), - 47
(0, 3), - 48
(-1, 3), - 49
(-2, 2), - 50
(-3, 1), - 51
(-3, 0), - 52
(-3, -1), - 53
(-2, -2), - 54
(-1, -3), - 55
] - 56
- 57
///| - 58
/// FAST-9 角点检测 - 59
fn fast_detect( - 60
gray : Array[Int32], - 61
w : Int32, - 62
h : Int32, - 63
threshold : Int32, - 64
) -> Array[OrbKeyPoint] { - 65●
let corners : Array[OrbKeyPoint] = [] - 66
for y in 3..<(h - 3) { - 67●
for x in 3..<(w - 3) { - 68●
let p = gray[y * w + x] - 69
let high_thresh = p + threshold - 70
let low_thresh = p - threshold - 71
// 读取圆周 16 个像素 - 72●
let vals : Array[Int32] = Array::make(16, 0) - 73
for i in 0..<16 { - 74●
let (dx, dy) = fast_offsets[i] - 75
vals[i] = gray[(y + dy) * w + (x + dx)] - 76
} - 77
// 检查是否有 9 个连续 brighter 或 darker - 78●
let is_corner = check_fast9(vals, high_thresh, low_thresh) - 79
if is_corner { - 80
// 计算方向 - 81●
let angle = compute_orientation(gray, w, h, x, y) - 82●
corners.push(OrbKeyPoint::{ x, y, response: 1.0F, angle, }) - 83
} - 84
} - 85
} - 86
corners - 87
} - 88
- 89
///| - 90
/// 检查 FAST-9 条件:圆周上是否有 9 个连续像素都 > high 或都 < low - 91
fn check_fast9(vals : Array[Int32], high : Int32, low : Int32) -> Bool { - 92
// 将 16 个点复制两遍以处理环绕 - 93●
let brighter : Array[Bool] = Array::make(32, false) - 94●
let darker : Array[Bool] = Array::make(32, false) - 95
for i in 0..<16 { - 96●
brighter[i] = vals[i] > high - 97
darker[i] = vals[i] < low - 98
brighter[i + 16] = brighter[i] - 99
darker[i + 16] = darker[i] - 100
} - 101
// 检查 9 连续 - 102
let mut b_run = 0 - 103
let mut d_run = 0 - 104
for i in 0..<32 { - 105●
if brighter[i] { - 106●
b_run += 1 - 107
if b_run >= 9 { - 108●
return true - 109
} - 110
} else { - 111●
b_run = 0 - 112
} - 113
if darker[i] { - 114●
d_run += 1 - 115
if d_run >= 9 { - 116●
return true - 117
} - 118
} else { - 119●
d_run = 0 - 120
} - 121
} - 122
false - 123
} - 124
- 125
///| - 126
/// 计算关键点方向(图像矩质心法) - 127
/// 方向角与矩 θ = atan2(m01, m10), m_pq = Σ x^p * y^q * I(x,y) - 128
fn compute_orientation( - 129
gray : Array[Int32], - 130
w : Int32, - 131
h : Int32, - 132
cx : Int32, - 133
cy : Int32, - 134
) -> Float { - 135●
let r = 15 // 取 31x31 patch - 136
let mut m01 = 0.0F - 137
let mut m10 = 0.0F - 138
for dy in -r..<=r { - 139●
let y = cy + dy - 140
if y < 0 || y >= h { - 141●
continue - 142
} - 143
for dx in -r..<=r { - 144●
let x = cx + dx - 145
if x < 0 || x >= w { - 146●
continue - 147
} - 148●
let v = Float::from_int(gray[y * w + x]) - 149●
m01 += Float::from_int(dy) * v - 150●
m10 += Float::from_int(dx) * v - 151
} - 152
} - 153●
Float::from_double(@math.atan2(m01.to_double(), m10.to_double())) - 154
} - 155
- 156
// ==================== BRIEF 描述子 ==================== - 157
- 158
///| - 159
/// 生成 BRIEF 采样点对(256 对) - 160
/// 使用固定伪随机模式(基于质心高斯分布) - 161
fn brief_pattern() -> Array[(Float, Float, Float, Float)] { - 162
// 256 个点对 (x1, y1, x2, y2),相对于关键点中心 - 163
// 使用固定模式确保可重复性 - 164●
let pairs : Array[(Float, Float, Float, Float)] = [] - 165
// 使用简单的 LCG 伪随机生成器 - 166
let mut seed = 12345 - 167
fn next_rand() -> Int32 { - 168●
seed = (seed * 1103515245 + 12345) & 0x7FFFFFFF - 169
seed - 170
} - 171
for _ in 0..<256 { - 172●
let x1 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F - 173●
let y1 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F - 174●
let x2 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F - 175●
let y2 = (Float::from_int(next_rand() % 48) - 24.0F) / 24.0F * 15.0F - 176●
pairs.push((x1, y1, x2, y2)) - 177
} - 178
pairs - 179
} - 180
- 181
///| - 182
/// 计算 rBRIEF 描述子(旋转后的 BRIEF) - 183
fn compute_brief( - 184
gray : Array[Int32], - 185
w : Int32, - 186
h : Int32, - 187
kp : OrbKeyPoint, - 188
pattern : Array[(Float, Float, Float, Float)], - 189
) -> Array[Int32] { - 190●
let desc : Array[Int32] = Array::make(32, 0) - 191●
let cos_a = Float::from_double(@math.cos(kp.angle.to_double())) - 192●
let sin_a = Float::from_double(@math.sin(kp.angle.to_double())) - 193
for i in 0..<256 { - 194●
let (x1, y1, x2, y2) = pattern[i] - 195
// 旋转采样点 - 196
let rx1 = x1 * cos_a - y1 * sin_a - 197
let ry1 = x1 * sin_a + y1 * cos_a - 198
let rx2 = x2 * cos_a - y2 * sin_a - 199
let ry2 = x2 * sin_a + y2 * cos_a - 200
// 采样像素值(双线性插值) - 201●
let v1 = sample_bilinear(gray, w, h, kp.x, kp.y, rx1, ry1) - 202●
let v2 = sample_bilinear(gray, w, h, kp.x, kp.y, rx2, ry2) - 203
// 二进制测试 - 204
if v1 < v2 { - 205●
let word = i / 32 - 206
let bit = i % 32 - 207
desc[word] = desc[word] | (1 << bit) - 208
} - 209
} - 210
desc - 211
} - 212
- 213
///| - 214
/// 双线性插值采样 - 215
fn sample_bilinear( - 216
gray : Array[Int32], - 217
w : Int32, - 218
h : Int32, - 219
cx : Int32, - 220
cy : Int32, - 221
dx : Float, - 222
dy : Float, - 223
) -> Int32 { - 224●
let fx = Float::from_int(cx) + dx - 225●
let fy = Float::from_int(cy) + dy - 226●
let x0 = fx.to_int() - 227●
let y0 = fy.to_int() - 228
let x1 = x0 + 1 - 229
let y1 = y0 + 1 - 230●
let x0c = x0.clamp(min=0, max=w - 1) - 231●
let x1c = x1.clamp(min=0, max=w - 1) - 232●
let y0c = y0.clamp(min=0, max=h - 1) - 233●
let y1c = y1.clamp(min=0, max=h - 1) - 234
let p00 = gray[y0c * w + x0c] - 235
let p01 = gray[y0c * w + x1c] - 236
let p10 = gray[y1c * w + x0c] - 237
let p11 = gray[y1c * w + x1c] - 238●
let wx = fx - Float::from_int(x0) - 239●
let wy = fy - Float::from_int(y0) - 240●
let v = Float::from_int(p00) * (1.0F - wx) * (1.0F - wy) + - 241●
Float::from_int(p01) * wx * (1.0F - wy) + - 242●
Float::from_int(p10) * (1.0F - wx) * wy + - 243●
Float::from_int(p11) * wx * wy - 244●
v.to_int() - 245
} - 246
- 247
// ==================== 灰度转换 ==================== - 248
- 249
///| - 250
fn to_gray_orb(img : @types.Image) -> (Array[Int32], Int32, Int32) { - 251●
let w = img.width - 252
let h = img.height - 253
let ch = img.channels - 254
let n = w * h - 255●
let gray : Array[Int32] = Array::make(n, 0) - 256
for i in 0..<n { - 257●
if ch >= 3 { - 258●
let r = img.data[i * ch].to_int() - 259●
let g = img.data[i * ch + 1].to_int() - 260●
let b = img.data[i * ch + 2].to_int() - 261
gray[i] = (r * 299 + g * 587 + b * 114) / 1000 - 262
} else { - 263●
gray[i] = img.data[i * ch].to_int() - 264
} - 265
} - 266
(gray, w, h) - 267
} - 268
- 269
// ==================== 公开 API ==================== - 270
- 271
///| - 272
/// ORB 特征检测。 - 273
/// 检测 FAST 关键点并计算 rBRIEF 描述子。 - 274
/// max_features 控制最大特征数,threshold 为 FAST 阈值。 - 275
pub fn orb_detect( - 276
img : @types.Image, - 277
max_features~ : Int32 = 500, - 278
threshold~ : Int32 = 20, - 279
) -> Array[OrbDescriptor] raise @types.LoadError { - 280
// 输入验证 - 281●
if img.width <= 0 || img.height <= 0 { - 282○
raise @types.LoadError::DecodeFailed( - 283
"orb_detect: 图像尺寸必须大于0", - 284
) - 285
} - 286
if img.width < 7 || img.height < 7 { - 287●
raise @types.LoadError::DecodeFailed( - 288
"orb_detect: ORB 需要至少 7x7 图像", - 289
) - 290
} - 291
if img.channels < 1 || img.channels > 4 { - 292○
raise @types.LoadError::DecodeFailed( - 293
"orb_detect: 通道数必须在1-4之间", - 294
) - 295
} - 296
let expected_size = img.width * img.height * img.channels - 297●
if img.data.length() != expected_size { - 298○
raise @types.LoadError::DecodeFailed( - 299
"orb_detect: 数据大小不匹配,期望 " + - 300○
expected_size.to_string() + - 301
",实际 " + - 302○
img.data.length().to_string(), - 303
) - 304
} - 305
if max_features <= 0 { - 306○
raise @types.LoadError::DecodeFailed( - 307
"orb_detect: max_features必须大于0", - 308
) - 309
} - 310
if threshold <= 0 || threshold > 255 { - 311○
raise @types.LoadError::DecodeFailed( - 312
"orb_detect: threshold必须在1-255范围内", - 313
) - 314
} - 315●
let (gray, w, h) = to_gray_orb(img) - 316
// FAST 检测 - 317●
let keypoints = fast_detect(gray, w, h, threshold) - 318
// 限制特征数:取前 max_features 个 - 319●
let kps = if keypoints.length() > max_features { - 320●
keypoints[0:max_features] - 321
} else { - 322●
keypoints - 323
} - 324
// 计算 BRIEF 描述子 - 325●
let pattern = brief_pattern() - 326
let descriptors : Array[OrbDescriptor] = [] - 327
for kp in kps { - 328●
let desc = compute_brief(gray, w, h, kp, pattern) - 329●
descriptors.push(OrbDescriptor::{ kp, data: desc, }) - 330
} - 331
descriptors - 332
} - 333
- 334
///| - 335
/// ORB 描述子汉明距离 - 336
pub fn orb_hamming(d1 : OrbDescriptor, d2 : OrbDescriptor) -> Int32 { - 337●
let mut dist = 0 - 338
for i in 0..<32 { - 339●
let xor = d1.data[i] ^ d2.data[i] - 340
// 计算位计数 - 341
let mut bits = xor - 342
bits = (bits & 0x55555555) + ((bits >> 1) & 0x55555555) - 343
bits = (bits & 0x33333333) + ((bits >> 2) & 0x33333333) - 344
bits = (bits & 0x0F0F0F0F) + ((bits >> 4) & 0x0F0F0F0F) - 345
bits = (bits & 0x00FF00FF) + ((bits >> 8) & 0x00FF00FF) - 346
bits = (bits & 0x0000FFFF) + ((bits >> 16) & 0x0000FFFF) - 347
dist += bits - 348
} - 349
dist - 350
} - 351
- 352
///| - 353
/// ORB 特征匹配。 - 354
/// 对 query 中每个描述子,找 train 中汉明距离最小的匹配。 - 355
/// max_distance 为最大允许距离(默认 64)。 - 356
pub fn orb_match( - 357
query : Array[OrbDescriptor], - 358
train : Array[OrbDescriptor], - 359
max_distance~ : Int32 = 64, - 360
) -> Array[DescriptorMatch] raise @types.LoadError { - 361
// 参数验证 - 362●
if query.length() == 0 { - 363●
raise @types.LoadError::DecodeFailed("orb_match: query数组不能为空") - 364
} - 365●
if train.length() == 0 { - 366○
raise @types.LoadError::DecodeFailed("orb_match: train数组不能为空") - 367
} - 368
if max_distance < 0 { - 369○
raise @types.LoadError::DecodeFailed("orb_match: max_distance必须 >= 0") - 370
} - 371
- 372
let matches : Array[DescriptorMatch] = [] - 373●
for i in 0..<query.length() { - 374●
let mut best_j = -1 - 375
let mut best_dist = max_distance + 1 - 376●
for j in 0..<train.length() { - 377●
let dist = orb_hamming(query[i], train[j]) - 378
if dist < best_dist { - 379●
best_dist = dist - 380
best_j = j - 381
} - 382
} - 383
if best_j >= 0 && best_dist <= max_distance { - 384●
matches.push(DescriptorMatch::{ - 385
query_idx: i, - 386
train_idx: best_j, - 387
distance: best_dist, - 388
}) - 389
} - 390
} - 391
matches - 392
}