image.vision\video\video_stabilization.mbt

95.2% · 99 / 104 points · 437 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/// # 视频防抖 video/video_stabilization
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 视频稳定 — 轨迹/平滑/裁剪
  7. 7// Video stabilization: trajectory / smoothing / cropping
  8. 8//
  9. 9// Phase 17 v396: 视频处理大扩展 — 视频稳定。
  10. 10
  11. 11///|
  12. 12/// 稳定方法。
  13. 13/// 防抖方法 Stabilization method.
  14. 14/// `#non_exhaustive` 表示未来可能添加新构造器
  15. 15#derive(Eq, @debug.Debug)
  16. 16#non_exhaustive
  17. 17pub(all) enum StabilizationMethod {
  18. 18 MotionModel // 运动模型(平移)
  19. 19 Affine // 仿射
  20. 20 Perspective // 透视
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend StabilizationMethod with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend StabilizationMethod with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 平滑方法。
  31. 31/// 平滑方法 Smoothing method.
  32. 32/// `#non_exhaustive` 表示未来可能添加新构造器
  33. 33#derive(Eq, @debug.Debug)
  34. 34#non_exhaustive
  35. 35pub(all) enum TrajectorySmoothing {
  36. 36 Gaussian // 高斯平滑
  37. 37 MovingAverage // 移动平均
  38. 38 MedianFilter // 中值滤波
  39. 39}
  40. 40
  41. 41///|
  42. 42pub extend TrajectorySmoothing with @debug.Debug::{to_repr}
  43. 43
  44. 44///|
  45. 45pub extend TrajectorySmoothing with Eq::{not_equal, equal}
  46. 46
  47. 47///|
  48. 48/// 轨迹点。
  49. 49/// 轨迹点 Trajectory point.
  50. 50#derive(Eq, @debug.Debug)
  51. 51pub(all) struct TrajectoryPoint {
  52. 52 x : Double
  53. 53 y : Double
  54. 54 frame_index : Int32
  55. 55}
  56. 56
  57. 57///|
  58. 58pub extend TrajectoryPoint with @debug.Debug::{to_repr}
  59. 59
  60. 60///|
  61. 61pub extend TrajectoryPoint with Eq::{not_equal, equal}
  62. 62
  63. 63///|
  64. 64/// 稳定配置。
  65. 65/// 防抖配置 Stabilization configuration.
  66. 66#derive(Eq, @debug.Debug)
  67. 67pub(all) struct StabilizationConfig {
  68. 68 stab_method : StabilizationMethod
  69. 69 smoothing : TrajectorySmoothing
  70. 70 smoothing_radius : Int32 // 平滑窗口半径
  71. 71 crop_margin : Double // 裁剪边距 (0.0-0.5)
  72. 72}
  73. 73
  74. 74///|
  75. 75pub extend StabilizationConfig with @debug.Debug::{to_repr}
  76. 76
  77. 77///|
  78. 78pub extend StabilizationConfig with Eq::{not_equal, equal}
  79. 79
  80. 80///|
  81. 81/// 稳定结果。
  82. 82/// 防抖结果 Stabilization result.
  83. 83#derive(Eq, @debug.Debug)
  84. 84pub(all) struct StabilizationResult {
  85. 85 frames : Array[@types.Image]
  86. 86 trajectory : Array[TrajectoryPoint]
  87. 87 smoothed_trajectory : Array[TrajectoryPoint]
  88. 88 crop_x : Int32
  89. 89 crop_y : Int32
  90. 90 crop_width : Int32
  91. 91 crop_height : Int32
  92. 92}
  93. 93
  94. 94///|
  95. 95pub extend StabilizationResult with @debug.Debug::{to_repr}
  96. 96
  97. 97///|
  98. 98pub extend StabilizationResult with Eq::{not_equal, equal}
  99. 99
  100. 100///|
  101. 101/// 默认稳定配置。
  102. 102/// 默认防抖配置 Default stabilization configuration.
  103. 103pub fn default_stabilization_config() -> StabilizationConfig {
  104. 104● {
  105. 105 stab_method: MotionModel,
  106. 106 smoothing: Gaussian,
  107. 107 smoothing_radius: 15,
  108. 108 crop_margin: 0.1,
  109. 109 }
  110. 110}
  111. 111
  112. 112///|
  113. 113/// 计算帧间运动轨迹。
  114. 114/// 计算帧间运动轨迹 Compute inter-frame motion trajectory.
  115. 115pub fn compute_trajectory(
  116. 116 frames : Array[@types.Image],
  117. 117) -> Array[TrajectoryPoint] {
  118. 118● let trajectory : Array[TrajectoryPoint] = []
  119. 119● let n = frames.length()
  120. 120 if n == 0 {
  121. 121● return trajectory
  122. 122 }
  123. 123 let mut cumul_x = 0.0
  124. 124 let mut cumul_y = 0.0
  125. 125● trajectory.push({ x: 0.0, y: 0.0, frame_index: 0, })
  126. 126 for i in 1..<n {
  127. 127● let prev = frames[i - 1]
  128. 128 let curr = frames[i]
  129. 129 // 简化:用帧间质心差作为运动
  130. 130● let (dx, dy) = compute_frame_offset(prev, curr)
  131. 131 cumul_x = cumul_x + dx
  132. 132 cumul_y = cumul_y + dy
  133. 133● trajectory.push({ x: cumul_x, y: cumul_y, frame_index: i, })
  134. 134 }
  135. 135 trajectory
  136. 136}
  137. 137
  138. 138///|
  139. 139/// 计算帧间偏移(简化:用质心差)。
  140. 140/// 计算帧偏移(简化:质心差) Compute frame offset (simplified: centroid difference).
  141. 141fn compute_frame_offset(
  142. 142 prev : @types.Image,
  143. 143 curr : @types.Image,
  144. 144) -> (Double, Double) {
  145. 145● let w = prev.width
  146. 146 let h = prev.height
  147. 147 let ch = prev.channels
  148. 148 let mut prev_cx = 0.0
  149. 149 let mut prev_cy = 0.0
  150. 150 let mut curr_cx = 0.0
  151. 151 let mut curr_cy = 0.0
  152. 152 let mut prev_weight = 0.0
  153. 153 let mut curr_weight = 0.0
  154. 154 for y in 0..<h {
  155. 155● for x in 0..<w {
  156. 156● let idx = (y * w + x) * ch
  157. 157● let pv = prev.data[idx].to_int().to_double()
  158. 158● let cv = curr.data[idx].to_int().to_double()
  159. 159● prev_cx = prev_cx + x.to_double() * pv
  160. 160● prev_cy = prev_cy + y.to_double() * pv
  161. 161● curr_cx = curr_cx + x.to_double() * cv
  162. 162● curr_cy = curr_cy + y.to_double() * cv
  163. 163 prev_weight = prev_weight + pv
  164. 164 curr_weight = curr_weight + cv
  165. 165 }
  166. 166 }
  167. 167 if prev_weight > 0.0 && curr_weight > 0.0 {
  168. 168● (
  169. 169 curr_cx / curr_weight - prev_cx / prev_weight,
  170. 170 curr_cy / curr_weight - prev_cy / prev_weight,
  171. 171 )
  172. 172 } else {
  173. 173○ (0.0, 0.0)
  174. 174 }
  175. 175}
  176. 176
  177. 177///|
  178. 178/// 高斯平滑轨迹。
  179. 179/// 轨迹高斯平滑 Gaussian smoothing of trajectory.
  180. 180fn gaussian_smooth(
  181. 181 trajectory : Array[TrajectoryPoint],
  182. 182 radius : Int32,
  183. 183) -> Array[TrajectoryPoint] {
  184. 184● let n = trajectory.length()
  185. 185 let result : Array[TrajectoryPoint] = []
  186. 186 for i in 0..<n {
  187. 187● let mut sum_x = 0.0
  188. 188 let mut sum_y = 0.0
  189. 189 let mut weight_sum = 0.0
  190. 190 for j in -radius..<=radius {
  191. 191● let idx = i + j
  192. 192 if idx >= 0 && idx < n {
  193. 193● let sigma = radius.to_double()
  194. 194● let w = @math.exp(
  195. 195● -(j.to_double() * j.to_double()) / (2.0 * sigma * sigma),
  196. 196 )
  197. 197 sum_x = sum_x + trajectory[idx].x * w
  198. 198 sum_y = sum_y + trajectory[idx].y * w
  199. 199 weight_sum = weight_sum + w
  200. 200 }
  201. 201 }
  202. 202 if weight_sum > 0.0 {
  203. 203● result.push({
  204. 204 x: sum_x / weight_sum,
  205. 205 y: sum_y / weight_sum,
  206. 206 frame_index: i,
  207. 207 })
  208. 208 } else {
  209. 209○ result.push(trajectory[i])
  210. 210 }
  211. 211 }
  212. 212 result
  213. 213}
  214. 214
  215. 215///|
  216. 216/// 移动平均平滑轨迹。
  217. 217/// 轨迹移动平均平滑 Moving average smoothing of trajectory.
  218. 218fn moving_average_smooth(
  219. 219 trajectory : Array[TrajectoryPoint],
  220. 220 radius : Int32,
  221. 221) -> Array[TrajectoryPoint] {
  222. 222● let n = trajectory.length()
  223. 223 let result : Array[TrajectoryPoint] = []
  224. 224 for i in 0..<n {
  225. 225● let mut sum_x = 0.0
  226. 226 let mut sum_y = 0.0
  227. 227 let mut count = 0.0
  228. 228 for j in -radius..<=radius {
  229. 229● let idx = i + j
  230. 230 if idx >= 0 && idx < n {
  231. 231● sum_x = sum_x + trajectory[idx].x
  232. 232 sum_y = sum_y + trajectory[idx].y
  233. 233 count = count + 1.0
  234. 234 }
  235. 235 }
  236. 236 if count > 0.0 {
  237. 237● result.push({ x: sum_x / count, y: sum_y / count, frame_index: i, })
  238. 238 } else {
  239. 239○ result.push(trajectory[i])
  240. 240 }
  241. 241 }
  242. 242 result
  243. 243}
  244. 244
  245. 245///|
  246. 246/// 中值滤波平滑轨迹。
  247. 247/// 轨迹中值滤波平滑 Median filter smoothing of trajectory.
  248. 248fn median_smooth(
  249. 249 trajectory : Array[TrajectoryPoint],
  250. 250 radius : Int32,
  251. 251) -> Array[TrajectoryPoint] {
  252. 252● let n = trajectory.length()
  253. 253 let result : Array[TrajectoryPoint] = []
  254. 254 for i in 0..<n {
  255. 255● let xs : Array[Double] = []
  256. 256 let ys : Array[Double] = []
  257. 257 for j in -radius..<=radius {
  258. 258● let idx = i + j
  259. 259 if idx >= 0 && idx < n {
  260. 260● xs.push(trajectory[idx].x)
  261. 261● ys.push(trajectory[idx].y)
  262. 262 }
  263. 263 }
  264. 264● xs.sort()
  265. 265● ys.sort()
  266. 266● let mid = xs.length() / 2
  267. 267● result.push({ x: xs[mid], y: ys[mid], frame_index: i, })
  268. 268 }
  269. 269 result
  270. 270}
  271. 271
  272. 272///|
  273. 273/// 平滑轨迹。
  274. 274/// 平滑轨迹 Smooth trajectory.
  275. 275pub fn smooth_trajectory(
  276. 276 trajectory : Array[TrajectoryPoint],
  277. 277 config : StabilizationConfig,
  278. 278) -> Array[TrajectoryPoint] {
  279. 279● match config.smoothing {
  280. 280● Gaussian => gaussian_smooth(trajectory, config.smoothing_radius)
  281. 281● MovingAverage => moving_average_smooth(trajectory, config.smoothing_radius)
  282. 282● MedianFilter => median_smooth(trajectory, config.smoothing_radius)
  283. 283 }
  284. 284}
  285. 285
  286. 286///|
  287. 287/// 平移图像。
  288. 288/// 平移图像 (dx, dy) Translate image by (dx, dy).
  289. 289fn translate_image(
  290. 290 img : @types.Image,
  291. 291 dx : Double,
  292. 292 dy : Double,
  293. 293) -> @types.Image {
  294. 294● let w = img.width
  295. 295 let h = img.height
  296. 296 let ch = img.channels
  297. 297 let data : Array[Byte] = []
  298. 298● let ix = dx.to_int()
  299. 299● let iy = dy.to_int()
  300. 300 for y in 0..<h {
  301. 301● for x in 0..<w {
  302. 302● let sx = x - ix
  303. 303 let sy = y - iy
  304. 304 for c in 0..<ch {
  305. 305● if sx >= 0 && sx < w && sy >= 0 && sy < h {
  306. 306● data.push(img.data[(sy * w + sx) * ch + c])
  307. 307 } else {
  308. 308● data.push((0 : Byte))
  309. 309 }
  310. 310 }
  311. 311 }
  312. 312 }
  313. 313● { width: w, height: h, channels: ch, data: Bytes::from_array(data), }
  314. 314}
  315. 315
  316. 316///|
  317. 317/// 稳定单帧。
  318. 318/// 稳定单帧 Stabilize a single frame.
  319. 319pub fn stabilize_frame(
  320. 320 img : @types.Image,
  321. 321 original_point : TrajectoryPoint,
  322. 322 smoothed_point : TrajectoryPoint,
  323. 323) -> @types.Image {
  324. 324 // 补偿 = 原始轨迹 - 平滑轨迹
  325. 325● let dx = original_point.x - smoothed_point.x
  326. 326 let dy = original_point.y - smoothed_point.y
  327. 327● translate_image(img, dx, dy)
  328. 328}
  329. 329
  330. 330///|
  331. 331/// 计算裁剪区域。
  332. 332/// 计算裁剪区域 Compute crop region.
  333. 333pub fn compute_crop_region(
  334. 334 width : Int32,
  335. 335 height : Int32,
  336. 336 margin : Double,
  337. 337) -> (Int32, Int32, Int32, Int32) {
  338. 338● let m = margin.clamp(min=0.0, max=0.5)
  339. 339● let crop_x = (width.to_double() * m).to_int()
  340. 340● let crop_y = (height.to_double() * m).to_int()
  341. 341 let crop_w = width - 2 * crop_x
  342. 342 let crop_h = height - 2 * crop_y
  343. 343 (crop_x, crop_y, crop_w, crop_h)
  344. 344}
  345. 345
  346. 346///|
  347. 347/// 裁剪图像到区域。
  348. 348/// 裁剪图像到区域 Crop image to region.
  349. 349fn crop_to_region(
  350. 350 img : @types.Image,
  351. 351 x : Int32,
  352. 352 y : Int32,
  353. 353 w : Int32,
  354. 354 h : Int32,
  355. 355) -> @types.Image {
  356. 356● let ch = img.channels
  357. 357 let data : Array[Byte] = []
  358. 358 for py in 0..<h {
  359. 359● for px in 0..<w {
  360. 360● let sx = (x + px).clamp(min=0, max=img.width - 1)
  361. 361● let sy = (y + py).clamp(min=0, max=img.height - 1)
  362. 362 for c in 0..<ch {
  363. 363● data.push(img.data[(sy * img.width + sx) * ch + c])
  364. 364 }
  365. 365 }
  366. 366 }
  367. 367● { width: w, height: h, channels: ch, data: Bytes::from_array(data), }
  368. 368}
  369. 369
  370. 370///|
  371. 371/// 稳定视频序列。
  372. 372/// 稳定视频序列 Stabilize video sequence.
  373. 373pub fn stabilize_video_sequence(
  374. 374 frames : Array[@types.Image],
  375. 375 config : StabilizationConfig,
  376. 376) -> StabilizationResult {
  377. 377● let n = frames.length()
  378. 378 if n == 0 {
  379. 379● return {
  380. 380 frames: [],
  381. 381 trajectory: [],
  382. 382 smoothed_trajectory: [],
  383. 383 crop_x: 0,
  384. 384 crop_y: 0,
  385. 385 crop_width: 0,
  386. 386 crop_height: 0,
  387. 387 }
  388. 388 }
  389. 389● let trajectory = compute_trajectory(frames)
  390. 390● let smoothed = smooth_trajectory(trajectory, config)
  391. 391 let stabilized : Array[@types.Image] = []
  392. 392 for i in 0..<n {
  393. 393● stabilized.push(stabilize_frame(frames[i], trajectory[i], smoothed[i]))
  394. 394 }
  395. 395 let w = frames[0].width
  396. 396 let h = frames[0].height
  397. 397● let (crop_x, crop_y, crop_w, crop_h) = compute_crop_region(
  398. 398 w,
  399. 399 h,
  400. 400 config.crop_margin,
  401. 401 )
  402. 402 let cropped : Array[@types.Image] = []
  403. 403 for frame in stabilized {
  404. 404● cropped.push(crop_to_region(frame, crop_x, crop_y, crop_w, crop_h))
  405. 405 }
  406. 406 {
  407. 407 frames: cropped,
  408. 408 trajectory,
  409. 409 smoothed_trajectory: smoothed,
  410. 410 crop_x,
  411. 411 crop_y,
  412. 412 crop_width: crop_w,
  413. 413 crop_height: crop_h,
  414. 414 }
  415. 415}
  416. 416
  417. 417///|
  418. 418/// 计算稳定度评分。
  419. 419/// 计算防抖质量分 Compute stabilization quality score.
  420. 420pub fn stabilization_score(
  421. 421 original_trajectory : Array[TrajectoryPoint],
  422. 422 smoothed_trajectory : Array[TrajectoryPoint],
  423. 423) -> Double {
  424. 424● let n = original_trajectory.length()
  425. 425 if n == 0 {
  426. 426● return 0.0
  427. 427 }
  428. 428 let mut total_jitter = 0.0
  429. 429 for i in 0..<n {
  430. 430● let dx = original_trajectory[i].x - smoothed_trajectory[i].x
  431. 431 let dy = original_trajectory[i].y - smoothed_trajectory[i].y
  432. 432● total_jitter = total_jitter + (dx * dx + dy * dy).sqrt()
  433. 433 }
  434. 434● let avg_jitter = total_jitter / n.to_double()
  435. 435 // 评分 = 100 / (1 + avg_jitter)
  436. 436 100.0 / (1.0 + avg_jitter)
  437. 437}