image.process\feature\optical_flow.mbt

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