image.vision\spatiotemporal\st_interpolate.mbt

82.1% · 23 / 28 points · 80 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/// # 时空插值 spatiotemporal/st_interpolate
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 帧间插值:线性插值 + 指定时间取帧。
  7. 7// Frame interpolation: linear blend + frame at specific time.
  8. 8
  9. 9///|
  10. 10/// 线性插值两帧图像:(1 - alpha) * frame1 + alpha * frame2。
  11. 11/// 两帧尺寸和通道数必须一致,alpha 通常在 [0, 1]。
  12. 12/// 两帧间线性插值 Linear interpolation between two frames
  13. 13pub fn st_interpolate_linear(
  14. 14 frame1 : @types.Image,
  15. 15 frame2 : @types.Image,
  16. 16 alpha : Float,
  17. 17) -> @types.Image raise @types.LoadError {
  18. 18● if frame1.width != frame2.width ||
  19. 19 frame1.height != frame2.height ||
  20. 20 frame1.channels != frame2.channels {
  21. 21● raise @types.LoadError::DecodeFailed(
  22. 22 "st_interpolate_linear: 两帧尺寸和通道数必须一致",
  23. 23 )
  24. 24 }
  25. 25 let w = frame1.width
  26. 26 let h = frame1.height
  27. 27 let ch = frame1.channels
  28. 28 let n = w * h * ch
  29. 29● let buf : Array[Byte] = Array::make(n, b'\x00')
  30. 30 let one_minus = 1.0F - alpha
  31. 31 for i in 0..<n {
  32. 32● let v1 = Float::from_int(frame1.data[i].to_int())
  33. 33● let v2 = Float::from_int(frame2.data[i].to_int())
  34. 34 let blended = one_minus * v1 + alpha * v2
  35. 35● buf[i] = (blended + 0.5F).to_int().clamp(min=0, max=255).to_byte()
  36. 36 }
  37. 37● { width: w, height: h, channels: ch, data: Bytes::from_array(buf), }
  38. 38}
  39. 39
  40. 40///|
  41. 41/// 在指定时间取帧:找到时间所在的帧区间,线性插值。
  42. 42/// 若时间超出范围且非循环,返回最近边界帧。
  43. 43/// 获取给定时间的插值帧 Get interpolated frame at the given time.
  44. 44pub fn st_interpolate_at(
  45. 45 timage : TImage,
  46. 46 time : Float,
  47. 47) -> @types.Image raise @types.LoadError {
  48. 48● if timage.frames.length() == 1 {
  49. 49● return timage.frames[0].image
  50. 50 }
  51. 51 // 计算累积时间,找到 time 所在的帧区间
  52. 52 let mut acc = 0.0F
  53. 53● for i in 0..<timage.frames.length() {
  54. 54● let frame = timage.frames[i]
  55. 55 let frame_end = acc + frame.duration
  56. 56○ if time < frame_end || i == timage.frames.length() - 1 {
  57. 57● if frame.duration <= 0.0F {
  58. 58○ return frame.image
  59. 59 }
  60. 60 let alpha = (time - acc) / frame.duration
  61. 61 let clamped_alpha = if alpha < 0.0F {
  62. 62○ 0.0F
  63. 63● } else if alpha > 1.0F {
  64. 64○ 1.0F
  65. 65 } else {
  66. 66● alpha
  67. 67 }
  68. 68● if i + 1 < timage.frames.length() {
  69. 69● return st_interpolate_linear(
  70. 70 frame.image,
  71. 71 timage.frames[i + 1].image,
  72. 72 clamped_alpha,
  73. 73 )
  74. 74 }
  75. 75 return frame.image
  76. 76 }
  77. 77 acc = frame_end
  78. 78 }
  79. 79○ timage.frames[timage.frames.length() - 1].image
  80. 80}