image.process\feature\optical_flow.mbt
100% · 116 / 116 points · 346 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 光流 optical flow - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// Lucas-Kanade 稀疏光流(纯 MoonBit) - 7
// 在两帧之间跟踪特征点的运动 - 8
// 参考: Lucas & Kanade, "An Iterative Image Registration Technique" - 9
// (1981) - 10
- 11
///| - 12
/// 光流结果 - 13
pub(all) struct FlowResult { - 14
x : Float // 原始 x 坐标 - 15
y : Float // 原始 y 坐标 - 16
u : Float // x 方向位移 - 17
v : Float // y 方向位移 - 18
found : Bool // 是否成功跟踪 - 19
} - 20
- 21
///| - 22
/// Lucas-Kanade 稀疏光流。 - 23
/// 在 prev 和 next 两帧之间跟踪 points 中的特征点。 - 24
/// window_size 为搜索窗口大小(默认15),max_iter 为迭代次数(默认20)。 - 25
/// 返回每个点的光流结果。 - 26
pub fn lucas_kanade( - 27
prev : @types.Image, - 28
next : @types.Image, - 29
points : Array[(Int32, Int32)], - 30
window_size~ : Int32 = 15, - 31
max_iter~ : Int32 = 20, - 32
) -> Array[FlowResult] raise @types.LoadError { - 33
// 输入验证 - 34●
if prev.width <= 0 || prev.height <= 0 { - 35●
raise @types.LoadError::DecodeFailed( - 36
"lucas_kanade: prev图像尺寸必须大于0", - 37
) - 38
} - 39
if next.width <= 0 || next.height <= 0 { - 40●
raise @types.LoadError::DecodeFailed( - 41
"lucas_kanade: next图像尺寸必须大于0", - 42
) - 43
} - 44
if prev.channels < 1 || prev.channels > 4 { - 45●
raise @types.LoadError::DecodeFailed( - 46
"lucas_kanade: prev通道数必须在1-4之间", - 47
) - 48
} - 49
if next.channels < 1 || next.channels > 4 { - 50●
raise @types.LoadError::DecodeFailed( - 51
"lucas_kanade: next通道数必须在1-4之间", - 52
) - 53
} - 54
let prev_expected_size = prev.width * prev.height * prev.channels - 55●
if prev.data.length() != prev_expected_size { - 56●
raise @types.LoadError::DecodeFailed( - 57
"lucas_kanade: prev数据大小不匹配,期望 " + - 58●
prev_expected_size.to_string() + - 59
",实际 " + - 60●
prev.data.length().to_string(), - 61
) - 62
} - 63
let next_expected_size = next.width * next.height * next.channels - 64●
if next.data.length() != next_expected_size { - 65●
raise @types.LoadError::DecodeFailed( - 66
"lucas_kanade: next数据大小不匹配,期望 " + - 67●
next_expected_size.to_string() + - 68
",实际 " + - 69●
next.data.length().to_string(), - 70
) - 71
} - 72
if prev.width != next.width || prev.height != next.height { - 73●
raise @types.LoadError::DecodeFailed( - 74
"lucas_kanade: 两帧图像尺寸必须一致", - 75
) - 76
} - 77●
if points.length() == 0 { - 78●
raise @types.LoadError::DecodeFailed( - 79
"lucas_kanade: points数组不能为空", - 80
) - 81
} - 82
if window_size < 3 || window_size > 31 || window_size % 2 == 0 { - 83●
raise @types.LoadError::DecodeFailed( - 84
"lucas_kanade: window_size必须为3..31之间的奇数", - 85
) - 86
} - 87
if max_iter <= 0 { - 88●
raise @types.LoadError::DecodeFailed("lucas_kanade: max_iter必须大于0") - 89
} - 90
let w = prev.width - 91
let h = prev.height - 92
// 转灰度 - 93●
let (gray_prev, _) = to_gray_lk(prev) - 94●
let (gray_next, _) = to_gray_lk(next) - 95
let half_win = window_size / 2 - 96
let results : Array[FlowResult] = [] - 97●
for i in 0..<points.length() { - 98●
let (px, py) = points[i] - 99
// 初始化位移 - 100
let mut u = 0.0F - 101
let mut v = 0.0F - 102
let mut found = false - 103
// 迭代求解 - 104
for _ in 0..<max_iter { - 105
// 构建 Lucas-Kanade 方程:A^T A * d = A^T b - 106●
let mut ixx = 0.0F - 107
let mut ixy = 0.0F - 108
let mut iyy = 0.0F - 109
let mut ix_it = 0.0F - 110
let mut iy_it = 0.0F - 111
for dy in -half_win..<=half_win { - 112●
for dx in -half_win..<=half_win { - 113●
let x = px + dx - 114
let y = py + dy - 115
if x < 1 || x >= w - 1 || y < 1 || y >= h - 1 { - 116●
continue - 117
} - 118
// 空间梯度(中心差分) - 119●
let ix = Float::from_int( - 120
gray_prev[y * w + x + 1] - gray_prev[y * w + x - 1], - 121
) / - 122
2.0F - 123●
let iy = Float::from_int( - 124
gray_prev[(y + 1) * w + x] - gray_prev[(y - 1) * w + x], - 125
) / - 126
2.0F - 127
// 时间差分:I_t = I_next(x+u, y+v) - I_prev(x, y) - 128●
let nx = Float::from_int(x) + u - 129●
let ny = Float::from_int(y) + v - 130●
let next_val = sample_bilinear_lk(gray_next, w, h, nx, ny) - 131●
let prev_val = Float::from_int(gray_prev[y * w + x]) - 132
let it = next_val - prev_val - 133
// 累加 A^T A 和 A^T b - 134
ixx += ix * ix - 135
ixy += ix * iy - 136
iyy += iy * iy - 137
ix_it += ix * it - 138
iy_it += iy * it - 139
} - 140
} - 141
// 求解 2x2 线性方程 - 142
let det = ixx * iyy - ixy * ixy - 143●
if det.abs() < 0.01F { - 144●
break - 145
} - 146
let du = -(iyy * ix_it - ixy * iy_it) / det - 147
let dv = -(ixx * iy_it - ixy * ix_it) / det - 148
u += du - 149
v += dv - 150
// 收敛检测 - 151●
if du.abs() < 0.01F && dv.abs() < 0.01F { - 152●
found = true - 153
break - 154
} - 155
found = true - 156
} - 157●
results.push(FlowResult::{ - 158●
x: Float::from_int(px), - 159●
y: Float::from_int(py), - 160
u, - 161
v, - 162
found, - 163
}) - 164
} - 165
results - 166
} - 167
- 168
///| - 169
/// Horn-Schunck 密集光流(简化版)。 - 170
/// 计算两帧之间所有像素的光流场。 - 171
/// alpha 为平滑权重(默认1.0),iterations 为迭代次数(默认100)。 - 172
/// 返回 (u_field, v_field),每个为 w*h 的 Float 数组。 - 173
pub fn horn_schunck( - 174
prev : @types.Image, - 175
next : @types.Image, - 176
alpha~ : Float = 1.0F, - 177
iterations~ : Int32 = 100, - 178
) -> (Array[Float], Array[Float]) raise @types.LoadError { - 179
// 输入验证 - 180●
if prev.width <= 0 || prev.height <= 0 { - 181●
raise @types.LoadError::DecodeFailed( - 182
"horn_schunck: prev图像尺寸必须大于0", - 183
) - 184
} - 185
if next.width <= 0 || next.height <= 0 { - 186●
raise @types.LoadError::DecodeFailed( - 187
"horn_schunck: next图像尺寸必须大于0", - 188
) - 189
} - 190
if prev.channels < 1 || prev.channels > 4 { - 191●
raise @types.LoadError::DecodeFailed( - 192
"horn_schunck: prev通道数必须在1-4之间", - 193
) - 194
} - 195
if next.channels < 1 || next.channels > 4 { - 196●
raise @types.LoadError::DecodeFailed( - 197
"horn_schunck: next通道数必须在1-4之间", - 198
) - 199
} - 200
let prev_expected_size = prev.width * prev.height * prev.channels - 201●
if prev.data.length() != prev_expected_size { - 202●
raise @types.LoadError::DecodeFailed( - 203
"horn_schunck: prev数据大小不匹配,期望 " + - 204●
prev_expected_size.to_string() + - 205
",实际 " + - 206●
prev.data.length().to_string(), - 207
) - 208
} - 209
let next_expected_size = next.width * next.height * next.channels - 210●
if next.data.length() != next_expected_size { - 211●
raise @types.LoadError::DecodeFailed( - 212
"horn_schunck: next数据大小不匹配,期望 " + - 213●
next_expected_size.to_string() + - 214
",实际 " + - 215●
next.data.length().to_string(), - 216
) - 217
} - 218
if prev.width != next.width || prev.height != next.height { - 219●
raise @types.LoadError::DecodeFailed( - 220
"horn_schunck: 两帧图像尺寸必须一致", - 221
) - 222
} - 223
if alpha <= 0.0F { - 224●
raise @types.LoadError::DecodeFailed("horn_schunck: alpha必须大于0") - 225
} - 226
if iterations <= 0 { - 227●
raise @types.LoadError::DecodeFailed( - 228
"horn_schunck: iterations必须大于0", - 229
) - 230
} - 231
let w = prev.width - 232
let h = prev.height - 233
let n = w * h - 234●
let (gray_prev, _) = to_gray_lk(prev) - 235●
let (gray_next, _) = to_gray_lk(next) - 236
// 计算空间梯度和时间梯度 - 237●
let ex : Array[Float] = Array::make(n, 0.0F) - 238●
let ey : Array[Float] = Array::make(n, 0.0F) - 239●
let et : Array[Float] = Array::make(n, 0.0F) - 240
for y in 0..<h { - 241●
for x in 0..<w { - 242●
let idx = y * w + x - 243●
let xl = if x > 0 { x - 1 } else { 0 } - 244●
let xr = if x < w - 1 { x + 1 } else { w - 1 } - 245●
let yu = if y > 0 { y - 1 } else { 0 } - 246●
let yd = if y < h - 1 { y + 1 } else { h - 1 } - 247
// Ex = (I(x+1,y) - I(x-1,y) + J(x+1,y) - J(x-1,y)) / 4 - 248●
ex[idx] = Float::from_int( - 249
gray_prev[y * w + xr] - - 250
gray_prev[y * w + xl] + - 251
gray_next[y * w + xr] - - 252
gray_next[y * w + xl], - 253
) / - 254
4.0F - 255
// Ey = (I(x,y+1) - I(x,y-1) + J(x,y+1) - J(x,y-1)) / 4 - 256●
ey[idx] = Float::from_int( - 257
gray_prev[yd * w + x] - - 258
gray_prev[yu * w + x] + - 259
gray_next[yd * w + x] - - 260
gray_next[yu * w + x], - 261
) / - 262
4.0F - 263
// Et = J(x,y) - I(x,y) - 264●
et[idx] = Float::from_int(gray_next[idx] - gray_prev[idx]) - 265
} - 266
} - 267
// 初始化光流场 - 268●
let u : Array[Float] = Array::make(n, 0.0F) - 269●
let v : Array[Float] = Array::make(n, 0.0F) - 270
let alpha_sq = alpha * alpha - 271
// 迭代求解 - 272
for _ in 0..<iterations { - 273●
let u_prev = u.copy() - 274●
let v_prev = v.copy() - 275
for y in 0..<h { - 276●
for x in 0..<w { - 277●
let idx = y * w + x - 278
// 计算 u, v 的邻域平均(4 邻域) - 279●
let xl = if x > 0 { idx - 1 } else { idx } - 280●
let xr = if x < w - 1 { idx + 1 } else { idx } - 281●
let yu = if y > 0 { idx - w } else { idx } - 282●
let yd = if y < h - 1 { idx + w } else { idx } - 283
let u_avg = (u_prev[xl] + u_prev[xr] + u_prev[yu] + u_prev[yd]) / 4.0F - 284
let v_avg = (v_prev[xl] + v_prev[xr] + v_prev[yu] + v_prev[yd]) / 4.0F - 285
// Horn-Schunck 更新 - 286
let denom = alpha_sq + ex[idx] * ex[idx] + ey[idx] * ey[idx] - 287
if denom > 0.0F { - 288●
let common = ex[idx] * u_avg + ey[idx] * v_avg + et[idx] - 289
u[idx] = u_avg - ex[idx] * common / denom - 290
v[idx] = v_avg - ey[idx] * common / denom - 291
} - 292
} - 293
} - 294
} - 295
(u, v) - 296
} - 297
- 298
// ==================== 辅助函数 ==================== - 299
- 300
///| - 301
fn to_gray_lk(img : @types.Image) -> (Array[Int32], Int32) { - 302●
let w = img.width - 303
let h = img.height - 304
let ch = img.channels - 305
let n = w * h - 306●
let gray : Array[Int32] = Array::make(n, 0) - 307
for i in 0..<n { - 308●
if ch >= 3 { - 309●
let r = img.data[i * ch].to_int() - 310●
let g = img.data[i * ch + 1].to_int() - 311●
let b = img.data[i * ch + 2].to_int() - 312
gray[i] = (r * 299 + g * 587 + b * 114) / 1000 - 313
} else { - 314●
gray[i] = img.data[i * ch].to_int() - 315
} - 316
} - 317
(gray, n) - 318
} - 319
- 320
///| - 321
fn sample_bilinear_lk( - 322
gray : Array[Int32], - 323
w : Int32, - 324
h : Int32, - 325
fx : Float, - 326
fy : Float, - 327
) -> Float { - 328●
let x0 = fx.to_int() - 329●
let y0 = fy.to_int() - 330
let x1 = x0 + 1 - 331
let y1 = y0 + 1 - 332●
let x0c = x0.clamp(min=0, max=w - 1) - 333●
let x1c = x1.clamp(min=0, max=w - 1) - 334●
let y0c = y0.clamp(min=0, max=h - 1) - 335●
let y1c = y1.clamp(min=0, max=h - 1) - 336
let p00 = gray[y0c * w + x0c] - 337
let p01 = gray[y0c * w + x1c] - 338
let p10 = gray[y1c * w + x0c] - 339
let p11 = gray[y1c * w + x1c] - 340●
let wx = fx - Float::from_int(x0) - 341●
let wy = fy - Float::from_int(y0) - 342●
Float::from_int(p00) * (1.0F - wx) * (1.0F - wy) + - 343●
Float::from_int(p01) * wx * (1.0F - wy) + - 344●
Float::from_int(p10) * (1.0F - wx) * wy + - 345●
Float::from_int(p11) * wx * wy - 346
}