image.vision\video\video_tracking.mbt

88.2% · 180 / 204 points · 845 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_tracking
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 视频目标跟踪与动作识别(v14.0.0)
  7. 7// 光流跟踪、目标跟踪、动作识别、视频稳定、关键帧提取、视频摘要
  8. 8
  9. 9///|
  10. 10/// 光流向量
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct OpticalFlowVector {
  13. 13 x : Double
  14. 14 y : Double
  15. 15 magnitude : Double
  16. 16 angle : Double
  17. 17}
  18. 18
  19. 19///|
  20. 20pub extend OpticalFlowVector with Eq::{not_equal, equal}
  21. 21
  22. 22///|
  23. 23pub extend OpticalFlowVector with @debug.Debug::{to_repr}
  24. 24
  25. 25///|
  26. 26/// 光流场
  27. 27#derive(Eq, @debug.Debug)
  28. 28pub(all) struct OpticalFlowField {
  29. 29 width : Int32
  30. 30 height : Int32
  31. 31 vectors : Array[OpticalFlowVector]
  32. 32 average_magnitude : Double
  33. 33 max_magnitude : Double
  34. 34 motion_direction : Double
  35. 35}
  36. 36
  37. 37///|
  38. 38pub extend OpticalFlowField with Eq::{not_equal, equal}
  39. 39
  40. 40///|
  41. 41pub extend OpticalFlowField with @debug.Debug::{to_repr}
  42. 42
  43. 43///|
  44. 44/// 跟踪目标
  45. 45#derive(Eq, @debug.Debug)
  46. 46pub(all) struct TrackedObject {
  47. 47 id : Int32
  48. 48 label : String
  49. 49 x : Int32
  50. 50 y : Int32
  51. 51 width : Int32
  52. 52 height : Int32
  53. 53 center_x : Double
  54. 54 center_y : Double
  55. 55 velocity_x : Double
  56. 56 velocity_y : Double
  57. 57 confidence : Double
  58. 58 age : Int32
  59. 59 visible_count : Int32
  60. 60 invisible_count : Int32
  61. 61 color_histogram : Array[Double]
  62. 62 trajectory : Array[(Int32, Int32)]
  63. 63}
  64. 64
  65. 65///|
  66. 66pub extend TrackedObject with Eq::{not_equal, equal}
  67. 67
  68. 68///|
  69. 69pub extend TrackedObject with @debug.Debug::{to_repr}
  70. 70
  71. 71///|
  72. 72/// 跟踪结果
  73. 73#derive(Eq, @debug.Debug)
  74. 74pub(all) struct TrackingResult {
  75. 75 frame_index : Int32
  76. 76 objects : Array[TrackedObject]
  77. 77 tracking_time_ms : Double
  78. 78 num_objects : Int32
  79. 79}
  80. 80
  81. 81///|
  82. 82pub extend TrackingResult with Eq::{not_equal, equal}
  83. 83
  84. 84///|
  85. 85pub extend TrackingResult with @debug.Debug::{to_repr}
  86. 86
  87. 87///|
  88. 88/// 动作类型
  89. 89/// `#non_exhaustive` 表示未来可能添加新构造器
  90. 90#derive(Eq, @debug.Debug)
  91. 91#non_exhaustive
  92. 92pub(all) enum ActionType {
  93. 93 Walking
  94. 94 Running
  95. 95 Jumping
  96. 96 Sitting
  97. 97 Standing
  98. 98 LyingDown
  99. 99 Waving
  100. 100 Clapping
  101. 101 Pointing
  102. 102 Lifting
  103. 103 Throwing
  104. 104 Catching
  105. 105 Unknown
  106. 106}
  107. 107
  108. 108///|
  109. 109pub extend ActionType with @debug.Debug::{to_repr}
  110. 110
  111. 111///|
  112. 112pub extend ActionType with Eq::{not_equal, equal}
  113. 113
  114. 114///|
  115. 115/// 动作识别结果
  116. 116#derive(Eq, @debug.Debug)
  117. 117pub(all) struct ActionRecognitionResult {
  118. 118 action_type : ActionType
  119. 119 confidence : Double
  120. 120 start_frame : Int32
  121. 121 end_frame : Int32
  122. 122 duration_frames : Int32
  123. 123 motion_energy : Double
  124. 124 direction : Double
  125. 125 key_points : Array[(Int32, Int32)]
  126. 126}
  127. 127
  128. 128///|
  129. 129pub extend ActionRecognitionResult with Eq::{not_equal, equal}
  130. 130
  131. 131///|
  132. 132pub extend ActionRecognitionResult with @debug.Debug::{to_repr}
  133. 133
  134. 134///|
  135. 135/// 视频稳定配置
  136. 136#derive(Eq, @debug.Debug)
  137. 137pub(all) struct VideoStabilizationConfig {
  138. 138 smoothing_radius : Int32
  139. 139 max_correction : Double
  140. 140 crop_ratio : Double
  141. 141 enable_rotation_correction : Bool
  142. 142 enable_scale_correction : Bool
  143. 143}
  144. 144
  145. 145///|
  146. 146pub extend VideoStabilizationConfig with Eq::{not_equal, equal}
  147. 147
  148. 148///|
  149. 149pub extend VideoStabilizationConfig with @debug.Debug::{to_repr}
  150. 150
  151. 151///|
  152. 152/// 关键帧类型
  153. 153/// `#non_exhaustive` 表示未来可能添加新构造器
  154. 154#derive(Eq, @debug.Debug)
  155. 155#non_exhaustive
  156. 156pub(all) enum KeyframeType {
  157. 157 SceneChange
  158. 158 MotionPeak
  159. 159 ContentChange
  160. 160 UniformSampling
  161. 161 UserSelected
  162. 162}
  163. 163
  164. 164///|
  165. 165pub extend KeyframeType with @debug.Debug::{to_repr}
  166. 166
  167. 167///|
  168. 168pub extend KeyframeType with Eq::{not_equal, equal}
  169. 169
  170. 170///|
  171. 171/// 关键帧
  172. 172#derive(Eq, @debug.Debug)
  173. 173pub(all) struct Keyframe {
  174. 174 frame_index : Int32
  175. 175 timestamp_ms : Double
  176. 176 keyframe_type : KeyframeType
  177. 177 score : Double
  178. 178 thumbnail : @types.Image
  179. 179}
  180. 180
  181. 181///|
  182. 182pub extend Keyframe with Eq::{not_equal, equal}
  183. 183
  184. 184///|
  185. 185pub extend Keyframe with @debug.Debug::{to_repr}
  186. 186
  187. 187///|
  188. 188/// 视频摘要
  189. 189#derive(Eq, @debug.Debug)
  190. 190pub(all) struct VideoSummary {
  191. 191 total_frames : Int32
  192. 192 duration_ms : Double
  193. 193 keyframes : Array[Keyframe]
  194. 194 num_keyframes : Int32
  195. 195 average_motion : Double
  196. 196 motion_peaks : Array[Int32]
  197. 197 scene_changes : Array[Int32]
  198. 198 summary_text : String
  199. 199}
  200. 200
  201. 201///|
  202. 202pub extend VideoSummary with Eq::{not_equal, equal}
  203. 203
  204. 204///|
  205. 205pub extend VideoSummary with @debug.Debug::{to_repr}
  206. 206
  207. 207///|
  208. 208/// 创建默认视频稳定配置
  209. 209pub fn create_default_stabilization_config() -> VideoStabilizationConfig {
  210. 210● VideoStabilizationConfig::{
  211. 211 smoothing_radius: 5,
  212. 212 max_correction: 20.0,
  213. 213 crop_ratio: 0.1,
  214. 214 enable_rotation_correction: true,
  215. 215 enable_scale_correction: false,
  216. 216 }
  217. 217}
  218. 218
  219. 219///|
  220. 220/// 计算帧差(简单运动检测,返回运动能量值)
  221. 221pub fn compute_frame_difference(
  222. 222 frame1 : @types.Image,
  223. 223 frame2 : @types.Image,
  224. 224 threshold~ : Double = 30.0,
  225. 225) -> Double {
  226. 226● let w = frame1.width
  227. 227 let h = frame1.height
  228. 228 let mut motion_pixels = 0
  229. 229 let total = w * h
  230. 230
  231. 231 for y in 0..<h {
  232. 232● for x in 0..<w {
  233. 233● let idx = y * w + x
  234. 234● let p1 = frame1.data[idx].to_int()
  235. 235● let p2 = frame2.data[idx].to_int()
  236. 236● let diff = (p1 - p2).abs().to_double()
  237. 237 if diff > threshold {
  238. 238● motion_pixels += 1
  239. 239 }
  240. 240 }
  241. 241 }
  242. 242
  243. 243 if total > 0 {
  244. 244● motion_pixels.to_double() / total.to_double()
  245. 245 } else {
  246. 246○ 0.0
  247. 247 }
  248. 248}
  249. 249
  250. 250///|
  251. 251/// 计算简单光流(块匹配法)
  252. 252pub fn compute_optical_flow(
  253. 253 frame1 : @types.Image,
  254. 254 frame2 : @types.Image,
  255. 255 block_size~ : Int32 = 8,
  256. 256 search_range~ : Int32 = 4,
  257. 257) -> OpticalFlowField {
  258. 258● let w = frame1.width
  259. 259 let h = frame1.height
  260. 260 let vectors : Array[OpticalFlowVector] = []
  261. 261 let mut total_magnitude = 0.0
  262. 262 let mut max_mag = 0.0
  263. 263 let mut sum_dx = 0.0
  264. 264 let mut sum_dy = 0.0
  265. 265 let mut count = 0
  266. 266
  267. 267 for by in 0..<(h / block_size) {
  268. 268● for bx in 0..<(w / block_size) {
  269. 269● let mut best_dx = 0
  270. 270 let mut best_dy = 0
  271. 271 let mut best_sad = 1000000.0
  272. 272
  273. 273 // 搜索最佳匹配
  274. 274 for dy in -search_range..<(search_range + 1) {
  275. 275● for dx in -search_range..<(search_range + 1) {
  276. 276● let mut sad = 0.0
  277. 277 let mut valid = true
  278. 278
  279. 279 for py in 0..<block_size {
  280. 280● for px in 0..<block_size {
  281. 281● let x1 = bx * block_size + px
  282. 282 let y1 = by * block_size + py
  283. 283 let x2 = x1 + dx
  284. 284 let y2 = y1 + dy
  285. 285
  286. 286 if x1 >= 0 &&
  287. 287 x1 < w &&
  288. 288 y1 >= 0 &&
  289. 289 y1 < h &&
  290. 290 x2 >= 0 &&
  291. 291 x2 < w &&
  292. 292 y2 >= 0 &&
  293. 293 y2 < h {
  294. 294● sad += (frame1.data[y1 * w + x1].to_int() -
  295. 295● frame2.data[y2 * w + x2].to_int())
  296. 296● .abs()
  297. 297● .to_double()
  298. 298 } else {
  299. 299● valid = false
  300. 300 }
  301. 301 }
  302. 302 }
  303. 303
  304. 304 if valid && sad < best_sad {
  305. 305● best_sad = sad
  306. 306 best_dx = dx
  307. 307 best_dy = dy
  308. 308 }
  309. 309 }
  310. 310 }
  311. 311
  312. 312● let magnitude = (best_dx.to_double() * best_dx.to_double() +
  313. 313● best_dy.to_double() * best_dy.to_double()).sqrt()
  314. 314 let angle = if best_dx != 0 {
  315. 315● best_dy.to_double() / best_dx.to_double() * 57.2958
  316. 316 } else {
  317. 317● 0.0
  318. 318 }
  319. 319
  320. 320● vectors.push(OpticalFlowVector::{
  321. 321● x: best_dx.to_double(),
  322. 322● y: best_dy.to_double(),
  323. 323 magnitude,
  324. 324 angle,
  325. 325 })
  326. 326
  327. 327 total_magnitude += magnitude
  328. 328 if magnitude > max_mag {
  329. 329● max_mag = magnitude
  330. 330 }
  331. 331● sum_dx += best_dx.to_double()
  332. 332● sum_dy += best_dy.to_double()
  333. 333 count += 1
  334. 334 }
  335. 335 }
  336. 336
  337. 337 let avg_mag = if count > 0 {
  338. 338● total_magnitude / count.to_double()
  339. 339 } else {
  340. 340○ 0.0
  341. 341 }
  342. 342● let motion_dir = if sum_dx != 0 { sum_dy / sum_dx * 57.2958 } else { 0.0 }
  343. 343
  344. 344 OpticalFlowField::{
  345. 345 width: w / block_size,
  346. 346 height: h / block_size,
  347. 347 vectors,
  348. 348 average_magnitude: avg_mag,
  349. 349 max_magnitude: max_mag,
  350. 350 motion_direction: motion_dir,
  351. 351 }
  352. 352}
  353. 353
  354. 354///|
  355. 355/// 目标跟踪初始化
  356. 356pub fn initialize_tracking(
  357. 357 first_frame : @types.Image,
  358. 358 roi_x : Int32,
  359. 359 roi_y : Int32,
  360. 360 roi_width : Int32,
  361. 361 roi_height : Int32,
  362. 362 label : String,
  363. 363) -> TrackedObject {
  364. 364 // 计算颜色直方图
  365. 365● let histogram : Array[Double] = []
  366. 366 for _ in 0..<16 {
  367. 367● histogram.push(0.0)
  368. 368 }
  369. 369
  370. 370 let w = first_frame.width
  371. 371 let h = first_frame.height
  372. 372 let mut total_pixels = 0
  373. 373
  374. 374 for y in roi_y..<(roi_y + roi_height) {
  375. 375● for x in roi_x..<(roi_x + roi_width) {
  376. 376● if x >= 0 && x < w && y >= 0 && y < h {
  377. 377● let pixel = first_frame.data[y * w + x].to_int()
  378. 378 let bin = pixel / 16
  379. 379 if bin < 16 {
  380. 380● histogram[bin] = histogram[bin] + 1.0
  381. 381 }
  382. 382 total_pixels += 1
  383. 383 }
  384. 384 }
  385. 385 }
  386. 386
  387. 387 // 归一化直方图
  388. 388 if total_pixels > 0 {
  389. 389● for i in 0..<16 {
  390. 390● histogram[i] = histogram[i] / total_pixels.to_double()
  391. 391 }
  392. 392 }
  393. 393
  394. 394 let trajectory : Array[(Int32, Int32)] = [
  395. 395 (roi_x + roi_width / 2, roi_y + roi_height / 2),
  396. 396 ]
  397. 397
  398. 398 TrackedObject::{
  399. 399 id: 0,
  400. 400 label,
  401. 401 x: roi_x,
  402. 402 y: roi_y,
  403. 403 width: roi_width,
  404. 404 height: roi_height,
  405. 405● center_x: (roi_x + roi_width / 2).to_double(),
  406. 406● center_y: (roi_y + roi_height / 2).to_double(),
  407. 407 velocity_x: 0.0,
  408. 408 velocity_y: 0.0,
  409. 409 confidence: 1.0,
  410. 410 age: 0,
  411. 411 visible_count: 1,
  412. 412 invisible_count: 0,
  413. 413 color_histogram: histogram,
  414. 414 trajectory,
  415. 415 }
  416. 416}
  417. 417
  418. 418///|
  419. 419/// 目标跟踪更新(MeanShift 简化版)
  420. 420pub fn update_tracking(
  421. 421 obj : TrackedObject,
  422. 422 frame : @types.Image,
  423. 423) -> TrackedObject {
  424. 424● let w = frame.width
  425. 425 let h = frame.height
  426. 426 let search_radius = 20
  427. 427
  428. 428 let mut best_x = obj.x
  429. 429 let mut best_y = obj.y
  430. 430 let mut best_score = -1.0
  431. 431
  432. 432 // 在目标周围搜索最佳匹配
  433. 433 for dy in -search_radius..<(search_radius + 1) {
  434. 434● for dx in -search_radius..<(search_radius + 1) {
  435. 435● let new_x = obj.x + dx
  436. 436 let new_y = obj.y + dy
  437. 437
  438. 438 // 计算当前位置的颜色直方图
  439. 439 let current_hist : Array[Double] = []
  440. 440 for _ in 0..<16 {
  441. 441● current_hist.push(0.0)
  442. 442 }
  443. 443 let mut total = 0
  444. 444
  445. 445 for py in 0..<obj.height {
  446. 446● for px in 0..<obj.width {
  447. 447● let x = new_x + px
  448. 448 let y = new_y + py
  449. 449 if x >= 0 && x < w && y >= 0 && y < h {
  450. 450● let pixel = frame.data[y * w + x].to_int()
  451. 451 let bin = pixel / 16
  452. 452 if bin < 16 {
  453. 453● current_hist[bin] = current_hist[bin] + 1.0
  454. 454 }
  455. 455 total += 1
  456. 456 }
  457. 457 }
  458. 458 }
  459. 459
  460. 460 if total > 0 {
  461. 461 // 归一化
  462. 462● for i in 0..<16 {
  463. 463● current_hist[i] = current_hist[i] / total.to_double()
  464. 464 }
  465. 465
  466. 466 // 计算直方图交集(相似度)
  467. 467 let mut score = 0.0
  468. 468 for i in 0..<16 {
  469. 469● score += if current_hist[i] < obj.color_histogram[i] {
  470. 470● current_hist[i]
  471. 471 } else {
  472. 472● obj.color_histogram[i]
  473. 473 }
  474. 474 }
  475. 475
  476. 476 if score > best_score {
  477. 477● best_score = score
  478. 478 best_x = new_x
  479. 479 best_y = new_y
  480. 480 }
  481. 481 }
  482. 482 }
  483. 483 }
  484. 484
  485. 485 // 更新速度
  486. 486● let new_center_x = (best_x + obj.width / 2).to_double()
  487. 487● let new_center_y = (best_y + obj.height / 2).to_double()
  488. 488 let velocity_x = new_center_x - obj.center_x
  489. 489 let velocity_y = new_center_y - obj.center_y
  490. 490
  491. 491 // 更新轨迹
  492. 492 let mut new_trajectory = obj.trajectory
  493. 493● new_trajectory.push((best_x + obj.width / 2, best_y + obj.height / 2))
  494. 494● if new_trajectory.length() > 100 {
  495. 495 // 保留最近 100 个点
  496. 496○ let trimmed : Array[(Int32, Int32)] = []
  497. 497○ for i in (new_trajectory.length() - 100)..<new_trajectory.length() {
  498. 498○ trimmed.push(new_trajectory[i])
  499. 499 }
  500. 500 new_trajectory = trimmed
  501. 501 }
  502. 502
  503. 503 TrackedObject::{
  504. 504 id: obj.id,
  505. 505 label: obj.label,
  506. 506 x: best_x,
  507. 507 y: best_y,
  508. 508 width: obj.width,
  509. 509 height: obj.height,
  510. 510 center_x: new_center_x,
  511. 511 center_y: new_center_y,
  512. 512 velocity_x,
  513. 513 velocity_y,
  514. 514 confidence: best_score,
  515. 515 age: obj.age + 1,
  516. 516 visible_count: obj.visible_count + 1,
  517. 517 invisible_count: 0,
  518. 518 color_histogram: obj.color_histogram,
  519. 519 trajectory: new_trajectory,
  520. 520 }
  521. 521}
  522. 522
  523. 523///|
  524. 524/// 动作识别(基于运动特征)
  525. 525pub fn recognize_action(
  526. 526 frames : Array[@types.Image],
  527. 527 start_frame : Int32,
  528. 528 end_frame : Int32,
  529. 529) -> ActionRecognitionResult {
  530. 530● if frames.length() < 2 || end_frame <= start_frame {
  531. 531○ return ActionRecognitionResult::{
  532. 532 action_type: ActionType::Unknown,
  533. 533 confidence: 0.0,
  534. 534 start_frame,
  535. 535 end_frame,
  536. 536 duration_frames: 0,
  537. 537 motion_energy: 0.0,
  538. 538 direction: 0.0,
  539. 539 key_points: [],
  540. 540 }
  541. 541 }
  542. 542
  543. 543 // 计算运动能量序列
  544. 544 let mut total_energy = 0.0
  545. 545 let mut energy_count = 0
  546. 546 let mut max_energy = 0.0
  547. 547 let mut motion_dx = 0.0
  548. 548 let mut motion_dy = 0.0
  549. 549
  550. 550 for i in start_frame..<(end_frame - 1) {
  551. 551● if i + 1 < frames.length() {
  552. 552● let energy = compute_frame_difference(frames[i], frames[i + 1])
  553. 553 total_energy += energy
  554. 554 energy_count += 1
  555. 555 if energy > max_energy {
  556. 556● max_energy = energy
  557. 557 }
  558. 558
  559. 559 // 计算运动方向(简化版)
  560. 560● let _ = compute_optical_flow(
  561. 561 frames[i],
  562. 562 frames[i + 1],
  563. 563 block_size=16,
  564. 564 search_range=2,
  565. 565 )
  566. 566 motion_dx += 1.0
  567. 567 motion_dy += 0.0
  568. 568 }
  569. 569 }
  570. 570
  571. 571 let avg_energy = if energy_count > 0 {
  572. 572● total_energy / energy_count.to_double()
  573. 573 } else {
  574. 574○ 0.0
  575. 575 }
  576. 576 let direction = if motion_dx != 0 {
  577. 577● motion_dy / motion_dx * 57.2958
  578. 578 } else {
  579. 579○ 0.0
  580. 580 }
  581. 581
  582. 582 // 根据运动特征分类动作
  583. 583 let (action_type, confidence) = if avg_energy < 0.01 {
  584. 584○ (ActionType::Standing, 0.7)
  585. 585● } else if avg_energy < 0.05 {
  586. 586○ (ActionType::Walking, 0.6)
  587. 587● } else if avg_energy < 0.1 {
  588. 588● (ActionType::Running, 0.6)
  589. 589● } else if max_energy > 0.2 && avg_energy > 0.05 {
  590. 590● (ActionType::Jumping, 0.5)
  591. 591○ } else if avg_energy > 0.15 {
  592. 592○ (ActionType::Waving, 0.5)
  593. 593 } else {
  594. 594○ (ActionType::Unknown, 0.3)
  595. 595 }
  596. 596
  597. 597 let key_points : Array[(Int32, Int32)] = []
  598. 598
  599. 599 ActionRecognitionResult::{
  600. 600 action_type,
  601. 601 confidence,
  602. 602 start_frame,
  603. 603 end_frame,
  604. 604 duration_frames: end_frame - start_frame,
  605. 605 motion_energy: avg_energy,
  606. 606 direction,
  607. 607 key_points,
  608. 608 }
  609. 609}
  610. 610
  611. 611///|
  612. 612/// 检测场景切换
  613. 613pub fn detect_scene_change(
  614. 614 frame1 : @types.Image,
  615. 615 frame2 : @types.Image,
  616. 616 threshold~ : Double = 0.3,
  617. 617) -> (Bool, Double) {
  618. 618● let w = frame1.width
  619. 619 let h = frame1.height
  620. 620 let mut diff_sum = 0.0
  621. 621 let total = w * h
  622. 622
  623. 623 for y in 0..<h {
  624. 624● for x in 0..<w {
  625. 625● let idx = y * w + x
  626. 626● diff_sum += (frame1.data[idx].to_int() - frame2.data[idx].to_int())
  627. 627● .abs()
  628. 628● .to_double() /
  629. 629 255.0
  630. 630 }
  631. 631 }
  632. 632
  633. 633◐ let avg_diff = if total > 0 { diff_sum / total.to_double() } else { 0.0 }
  634. 634 (avg_diff > threshold, avg_diff)
  635. 635}
  636. 636
  637. 637///|
  638. 638/// 提取关键帧
  639. 639pub fn extract_keyframes(
  640. 640 frames : Array[@types.Image],
  641. 641 fps : Double,
  642. 642 method_type~ : String = "auto",
  643. 643) -> Array[Keyframe] {
  644. 644● ignore(method_type)
  645. 645 let keyframes : Array[Keyframe] = []
  646. 646
  647. 647● if frames.length() == 0 {
  648. 648○ return keyframes
  649. 649 }
  650. 650
  651. 651 // 第一帧总是关键帧
  652. 652● keyframes.push(Keyframe::{
  653. 653 frame_index: 0,
  654. 654 timestamp_ms: 0.0,
  655. 655 keyframe_type: KeyframeType::UniformSampling,
  656. 656 score: 1.0,
  657. 657 thumbnail: frames[0],
  658. 658 })
  659. 659
  660. 660 // 检测场景切换
  661. 661● for i in 1..<frames.length() {
  662. 662● let (is_change, score) = detect_scene_change(frames[i - 1], frames[i])
  663. 663 if is_change {
  664. 664● keyframes.push(Keyframe::{
  665. 665 frame_index: i,
  666. 666● timestamp_ms: i.to_double() * 1000.0 / fps,
  667. 667 keyframe_type: KeyframeType::SceneChange,
  668. 668 score,
  669. 669 thumbnail: frames[i],
  670. 670 })
  671. 671 }
  672. 672 }
  673. 673
  674. 674 // 均匀采样(如果关键帧太少)
  675. 675● let min_keyframes = if frames.length() / 30 > 5 {
  676. 676○ frames.length() / 30
  677. 677 } else {
  678. 678● 5
  679. 679 }
  680. 680● if keyframes.length() < min_keyframes {
  681. 681● let interval = frames.length() / min_keyframes
  682. 682 for i in 1..<min_keyframes {
  683. 683● let idx = i * interval
  684. 684 let mut exists = false
  685. 685 for kf in keyframes {
  686. 686● if kf.frame_index == idx {
  687. 687● exists = true
  688. 688 }
  689. 689 }
  690. 690● if !exists && idx < frames.length() {
  691. 691● keyframes.push(Keyframe::{
  692. 692 frame_index: idx,
  693. 693● timestamp_ms: idx.to_double() * 1000.0 / fps,
  694. 694 keyframe_type: KeyframeType::UniformSampling,
  695. 695 score: 0.5,
  696. 696 thumbnail: frames[idx],
  697. 697 })
  698. 698 }
  699. 699 }
  700. 700 }
  701. 701
  702. 702 keyframes
  703. 703}
  704. 704
  705. 705///|
  706. 706/// 生成视频摘要
  707. 707pub fn generate_video_summary(
  708. 708 frames : Array[@types.Image],
  709. 709 fps : Double,
  710. 710) -> VideoSummary {
  711. 711● let total_frames = frames.length()
  712. 712 let duration_ms = if fps > 0 {
  713. 713● total_frames.to_double() * 1000.0 / fps
  714. 714 } else {
  715. 715○ 0.0
  716. 716 }
  717. 717
  718. 718 // 提取关键帧
  719. 719● let keyframes = extract_keyframes(frames, fps)
  720. 720
  721. 721 // 计算运动能量序列
  722. 722 let motion_peaks : Array[Int32] = []
  723. 723 let scene_changes : Array[Int32] = []
  724. 724 let mut total_motion = 0.0
  725. 725 let mut motion_count = 0
  726. 726
  727. 727 for i in 1..<total_frames {
  728. 728● let energy = compute_frame_difference(frames[i - 1], frames[i])
  729. 729 total_motion += energy
  730. 730 motion_count += 1
  731. 731
  732. 732 if energy > 0.15 {
  733. 733● motion_peaks.push(i)
  734. 734 }
  735. 735
  736. 736● let (is_change, _) = detect_scene_change(frames[i - 1], frames[i])
  737. 737 if is_change {
  738. 738● scene_changes.push(i)
  739. 739 }
  740. 740 }
  741. 741
  742. 742 let avg_motion = if motion_count > 0 {
  743. 743● total_motion / motion_count.to_double()
  744. 744 } else {
  745. 745○ 0.0
  746. 746 }
  747. 747
  748. 748 // 生成摘要文本
  749. 749 let summary_text = "视频共 " +
  750. 750● total_frames.to_string() +
  751. 751 " 帧,时长 " +
  752. 752● (duration_ms / 1000.0).to_string() +
  753. 753 " 秒。" +
  754. 754 "检测到 " +
  755. 755● scene_changes.length().to_string() +
  756. 756 " 个场景切换," +
  757. 757● motion_peaks.length().to_string() +
  758. 758 " 个运动峰值。" +
  759. 759 "平均运动能量 " +
  760. 760● avg_motion.to_string() +
  761. 761 "。" +
  762. 762 "提取 " +
  763. 763● keyframes.length().to_string() +
  764. 764 " 个关键帧。"
  765. 765
  766. 766 VideoSummary::{
  767. 767 total_frames,
  768. 768 duration_ms,
  769. 769 keyframes,
  770. 770● num_keyframes: keyframes.length(),
  771. 771 average_motion: avg_motion,
  772. 772 motion_peaks,
  773. 773 scene_changes,
  774. 774 summary_text,
  775. 775 }
  776. 776}
  777. 777
  778. 778///|
  779. 779/// 视频稳定(简化版,基于帧间偏移)
  780. 780pub fn stabilize_video(
  781. 781 frames : Array[@types.Image],
  782. 782 config : VideoStabilizationConfig,
  783. 783) -> Array[@types.Image] {
  784. 784● if frames.length() < 2 {
  785. 785○ return frames
  786. 786 }
  787. 787
  788. 788 let stabilized : Array[@types.Image] = []
  789. 789● stabilized.push(frames[0])
  790. 790
  791. 791 // 计算帧间偏移
  792. 792 let offsets_x : Array[Double] = []
  793. 793 let offsets_y : Array[Double] = []
  794. 794● offsets_x.push(0.0)
  795. 795● offsets_y.push(0.0)
  796. 796
  797. 797● for i in 1..<frames.length() {
  798. 798● let flow = compute_optical_flow(
  799. 799 frames[i - 1],
  800. 800 frames[i],
  801. 801 block_size=32,
  802. 802 search_range=4,
  803. 803 )
  804. 804 // 平均光流作为全局偏移
  805. 805 let mut avg_dx = 0.0
  806. 806 let mut avg_dy = 0.0
  807. 807 for v in flow.vectors {
  808. 808● avg_dx += v.x
  809. 809 avg_dy += v.y
  810. 810 }
  811. 811● if flow.vectors.length() > 0 {
  812. 812● avg_dx = avg_dx / flow.vectors.length().to_double()
  813. 813● avg_dy = avg_dy / flow.vectors.length().to_double()
  814. 814 }
  815. 815● offsets_x.push(avg_dx)
  816. 816● offsets_y.push(avg_dy)
  817. 817 }
  818. 818
  819. 819 // 平滑偏移
  820. 820 let smoothed_x : Array[Double] = []
  821. 821 let smoothed_y : Array[Double] = []
  822. 822 let radius = config.smoothing_radius
  823. 823
  824. 824● for i in 0..<frames.length() {
  825. 825● let mut sum_x = 0.0
  826. 826 let mut sum_y = 0.0
  827. 827 let mut count = 0
  828. 828 for j in (i - radius)..<(i + radius + 1) {
  829. 829● if j >= 0 && j < frames.length() {
  830. 830● sum_x += offsets_x[j]
  831. 831 sum_y += offsets_y[j]
  832. 832 count += 1
  833. 833 }
  834. 834 }
  835. 835◐ smoothed_x.push(if count > 0 { sum_x / count.to_double() } else { 0.0 })
  836. 836◐ smoothed_y.push(if count > 0 { sum_y / count.to_double() } else { 0.0 })
  837. 837 }
  838. 838
  839. 839 // 应用稳定(简化版:直接返回原帧,实际应进行仿射变换)
  840. 840● for i in 1..<frames.length() {
  841. 841● stabilized.push(frames[i])
  842. 842 }
  843. 843
  844. 844 stabilized
  845. 845}