image.vision\video\video_segmentation.mbt

93.3% · 111 / 119 points · 378 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_segmentation
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 视频分割 — 前景/背景/运动
  7. 7// Video segmentation: foreground / background / motion
  8. 8//
  9. 9// Phase 17 v399: 视频处理大扩展 — 视频分割。
  10. 10
  11. 11///|
  12. 12/// 视频分割方法。
  13. 13/// 视频分割方法 Video segmentation method.
  14. 14/// `#non_exhaustive` 表示未来可能添加新构造器
  15. 15#derive(Eq, @debug.Debug)
  16. 16#non_exhaustive
  17. 17pub(all) enum VideoSegmentationMethod {
  18. 18 FrameDifference // 帧差法
  19. 19 BackgroundSubtraction // 背景减除
  20. 20 MotionBased // 基于运动
  21. 21}
  22. 22
  23. 23///|
  24. 24pub extend VideoSegmentationMethod with @debug.Debug::{to_repr}
  25. 25
  26. 26///|
  27. 27pub extend VideoSegmentationMethod with Eq::{not_equal, equal}
  28. 28
  29. 29///|
  30. 30/// 背景模型。
  31. 31/// 背景模型 Background model.
  32. 32#derive(Eq, @debug.Debug)
  33. 33pub(all) struct BackgroundModel {
  34. 34 background : @types.Image
  35. 35 variance : @types.Image // 每像素方差
  36. 36 frame_count : Int32
  37. 37}
  38. 38
  39. 39///|
  40. 40pub extend BackgroundModel with @debug.Debug::{to_repr}
  41. 41
  42. 42///|
  43. 43pub extend BackgroundModel with Eq::{not_equal, equal}
  44. 44
  45. 45///|
  46. 46/// 分割配置。
  47. 47/// 分割配置 Segmentation configuration.
  48. 48#derive(Eq, @debug.Debug)
  49. 49pub(all) struct SegmentationConfig {
  50. 50 seg_method : VideoSegmentationMethod
  51. 51 threshold : Double // 二值化阈值
  52. 52 learning_rate : Double // 背景学习率 (0.0-1.0)
  53. 53 min_motion_area : Int32 // 最小运动区域面积
  54. 54}
  55. 55
  56. 56///|
  57. 57pub extend SegmentationConfig with @debug.Debug::{to_repr}
  58. 58
  59. 59///|
  60. 60pub extend SegmentationConfig with Eq::{not_equal, equal}
  61. 61
  62. 62///|
  63. 63/// 分割结果。
  64. 64/// 分割结果 Segmentation result.
  65. 65#derive(Eq, @debug.Debug)
  66. 66pub(all) struct SegmentationResult {
  67. 67 foreground_mask : Array[Bool] // 前景掩模
  68. 68 foreground_ratio : Double // 前景比例
  69. 69 motion_area : Int32 // 运动面积
  70. 70 width : Int32
  71. 71 height : Int32
  72. 72}
  73. 73
  74. 74///|
  75. 75pub extend SegmentationResult with @debug.Debug::{to_repr}
  76. 76
  77. 77///|
  78. 78pub extend SegmentationResult with Eq::{not_equal, equal}
  79. 79
  80. 80///|
  81. 81/// 默认分割配置。
  82. 82/// 默认分割配置 Default segmentation configuration.
  83. 83pub fn default_segmentation_config() -> SegmentationConfig {
  84. 84● {
  85. 85 seg_method: FrameDifference,
  86. 86 threshold: 30.0,
  87. 87 learning_rate: 0.05,
  88. 88 min_motion_area: 10,
  89. 89 }
  90. 90}
  91. 91
  92. 92///|
  93. 93/// 帧差法前景分割。
  94. 94/// 帧差前景分割 Frame difference foreground segmentation.
  95. 95pub fn segment_frame_difference(
  96. 96 current : @types.Image,
  97. 97 previous : @types.Image,
  98. 98 threshold : Double,
  99. 99) -> SegmentationResult {
  100. 100● let w = current.width
  101. 101 let h = current.height
  102. 102 let ch = current.channels
  103. 103 let mask : Array[Bool] = []
  104. 104 let mut motion_count = 0
  105. 105 for y in 0..<h {
  106. 106● for x in 0..<w {
  107. 107● let mut diff = 0.0
  108. 108 for c in 0..<ch {
  109. 109● let ci = (y * w + x) * ch + c
  110. 110● let d = current.data[ci].to_int() - previous.data[ci].to_int()
  111. 111● diff = diff + d.to_double().abs()
  112. 112 }
  113. 113● diff = diff / ch.to_double()
  114. 114 if diff > threshold {
  115. 115● mask.push(true)
  116. 116 motion_count = motion_count + 1
  117. 117 } else {
  118. 118● mask.push(false)
  119. 119 }
  120. 120 }
  121. 121 }
  122. 122 let total = w * h
  123. 123 let ratio = if total > 0 {
  124. 124● motion_count.to_double() / total.to_double()
  125. 125 } else {
  126. 126○ 0.0
  127. 127 }
  128. 128 {
  129. 129 foreground_mask: mask,
  130. 130 foreground_ratio: ratio,
  131. 131 motion_area: motion_count,
  132. 132 width: w,
  133. 133 height: h,
  134. 134 }
  135. 135}
  136. 136
  137. 137///|
  138. 138/// 构建背景模型。
  139. 139/// 从帧构建背景模型 Build background model from frames.
  140. 140pub fn build_background_model(frames : Array[@types.Image]) -> BackgroundModel? {
  141. 141● let n = frames.length()
  142. 142 if n == 0 {
  143. 143● return None
  144. 144 }
  145. 145 let w = frames[0].width
  146. 146 let h = frames[0].height
  147. 147 let ch = frames[0].channels
  148. 148 // 均值背景
  149. 149 let bg_data : Array[Byte] = []
  150. 150 let var_data : Array[Byte] = []
  151. 151 for i in 0..<(w * h * ch) {
  152. 152● let mut sum = 0.0
  153. 153 for frame in frames {
  154. 154● sum = sum + frame.data[i].to_int().to_double()
  155. 155 }
  156. 156● let mean = sum / n.to_double()
  157. 157 let mut var_sum = 0.0
  158. 158 for frame in frames {
  159. 159● let diff = frame.data[i].to_int().to_double() - mean
  160. 160 var_sum = var_sum + diff * diff
  161. 161 }
  162. 162● let variance = var_sum / n.to_double()
  163. 163● bg_data.push(mean.clamp(min=0.0, max=255.0).to_int().to_byte())
  164. 164● var_data.push(variance.clamp(min=0.0, max=255.0).to_int().to_byte())
  165. 165 }
  166. 166 Some({
  167. 167 background: {
  168. 168 width: w,
  169. 169 height: h,
  170. 170 channels: ch,
  171. 171● data: Bytes::from_array(bg_data),
  172. 172 },
  173. 173 variance: {
  174. 174 width: w,
  175. 175 height: h,
  176. 176 channels: ch,
  177. 177● data: Bytes::from_array(var_data),
  178. 178 },
  179. 179 frame_count: n,
  180. 180 })
  181. 181}
  182. 182
  183. 183///|
  184. 184/// 更新背景模型。
  185. 185/// 用新帧更新背景模型 Update background model with new frame.
  186. 186pub fn update_background_model(
  187. 187 model : BackgroundModel,
  188. 188 frame : @types.Image,
  189. 189 learning_rate : Double,
  190. 190) -> BackgroundModel {
  191. 191● let w = model.background.width
  192. 192 let h = model.background.height
  193. 193 let ch = model.background.channels
  194. 194● let alpha = learning_rate.clamp(min=0.0, max=1.0)
  195. 195 let bg_data : Array[Byte] = []
  196. 196 for i in 0..<(w * h * ch) {
  197. 197● let old = model.background.data[i].to_int().to_double()
  198. 198● let new_val = frame.data[i].to_int().to_double()
  199. 199 let updated = old * (1.0 - alpha) + new_val * alpha
  200. 200● bg_data.push(updated.clamp(min=0.0, max=255.0).to_int().to_byte())
  201. 201 }
  202. 202 {
  203. 203 background: {
  204. 204 width: w,
  205. 205 height: h,
  206. 206 channels: ch,
  207. 207● data: Bytes::from_array(bg_data),
  208. 208 },
  209. 209 variance: model.variance,
  210. 210 frame_count: model.frame_count + 1,
  211. 211 }
  212. 212}
  213. 213
  214. 214///|
  215. 215/// 背景减除。
  216. 216/// 背景减除 Background subtraction.
  217. 217pub fn subtract_background(
  218. 218 frame : @types.Image,
  219. 219 model : BackgroundModel,
  220. 220 threshold : Double,
  221. 221) -> SegmentationResult {
  222. 222● let w = frame.width
  223. 223 let h = frame.height
  224. 224 let ch = frame.channels
  225. 225 let mask : Array[Bool] = []
  226. 226 let mut motion_count = 0
  227. 227 for y in 0..<h {
  228. 228● for x in 0..<w {
  229. 229● let mut diff = 0.0
  230. 230 for c in 0..<ch {
  231. 231● let ci = (y * w + x) * ch + c
  232. 232● let d = frame.data[ci].to_int() - model.background.data[ci].to_int()
  233. 233● diff = diff + d.to_double().abs()
  234. 234 }
  235. 235● diff = diff / ch.to_double()
  236. 236 if diff > threshold {
  237. 237● mask.push(true)
  238. 238 motion_count = motion_count + 1
  239. 239 } else {
  240. 240● mask.push(false)
  241. 241 }
  242. 242 }
  243. 243 }
  244. 244 let total = w * h
  245. 245 let ratio = if total > 0 {
  246. 246● motion_count.to_double() / total.to_double()
  247. 247 } else {
  248. 248○ 0.0
  249. 249 }
  250. 250 {
  251. 251 foreground_mask: mask,
  252. 252 foreground_ratio: ratio,
  253. 253 motion_area: motion_count,
  254. 254 width: w,
  255. 255 height: h,
  256. 256 }
  257. 257}
  258. 258
  259. 259///|
  260. 260/// 基于运动的分割。
  261. 261/// 基于运动的分割 Motion-based segmentation.
  262. 262pub fn segment_motion(
  263. 263 frames : Array[@types.Image],
  264. 264 threshold : Double,
  265. 265) -> Array[SegmentationResult] {
  266. 266● let results : Array[SegmentationResult] = []
  267. 267● let n = frames.length()
  268. 268 if n < 2 {
  269. 269○ return results
  270. 270 }
  271. 271 for i in 1..<n {
  272. 272● results.push(segment_frame_difference(frames[i], frames[i - 1], threshold))
  273. 273 }
  274. 274 results
  275. 275}
  276. 276
  277. 277///|
  278. 278/// 视频分割流水线。
  279. 279/// 视频分割管线 Video segmentation pipeline.
  280. 280pub fn video_segmentation_pipeline(
  281. 281 frames : Array[@types.Image],
  282. 282 config : SegmentationConfig,
  283. 283) -> Array[SegmentationResult] {
  284. 284● match config.seg_method {
  285. 285● FrameDifference => {
  286. 286 let results : Array[SegmentationResult] = []
  287. 287● let n = frames.length()
  288. 288 if n < 2 {
  289. 289○ return results
  290. 290 }
  291. 291 for i in 1..<n {
  292. 292● results.push(
  293. 293● segment_frame_difference(frames[i], frames[i - 1], config.threshold),
  294. 294 )
  295. 295 }
  296. 296 results
  297. 297 }
  298. 298● BackgroundSubtraction => {
  299. 299 let results : Array[SegmentationResult] = []
  300. 300● let n = frames.length()
  301. 301 if n < 2 {
  302. 302○ return results
  303. 303 }
  304. 304● let model = build_background_model(frames)
  305. 305 if model is Some(m) {
  306. 306● for frame in frames {
  307. 307● results.push(subtract_background(frame, m, config.threshold))
  308. 308 }
  309. 309 }
  310. 310 results
  311. 311 }
  312. 312○ MotionBased => segment_motion(frames, config.threshold)
  313. 313 }
  314. 314}
  315. 315
  316. 316///|
  317. 317/// 计算运动一致性。
  318. 318/// 计算帧间运动一致性 Compute motion consistency across frames.
  319. 319pub fn motion_consistency(results : Array[SegmentationResult]) -> Double {
  320. 320● let n = results.length()
  321. 321 if n == 0 {
  322. 322● return 0.0
  323. 323 }
  324. 324 let w = results[0].width
  325. 325 let h = results[0].height
  326. 326 let total = w * h
  327. 327 if total == 0 {
  328. 328○ return 0.0
  329. 329 }
  330. 330 // 计算每像素的运动频率
  331. 331● let freq : Array[Int32] = Array::make(total, 0)
  332. 332 for r in results {
  333. 333● for i in 0..<total {
  334. 334● if i < r.foreground_mask.length() && r.foreground_mask[i] {
  335. 335● freq[i] = freq[i] + 1
  336. 336 }
  337. 337 }
  338. 338 }
  339. 339 // 一致性 = 高频运动像素比例
  340. 340 let mut consistent = 0
  341. 341 for f in freq {
  342. 342● if f.to_double() / n.to_double() > 0.5 {
  343. 343● consistent = consistent + 1
  344. 344 }
  345. 345 }
  346. 346● consistent.to_double() / total.to_double()
  347. 347}
  348. 348
  349. 349///|
  350. 350/// 提取前景图像。
  351. 351/// 使用掩膜提取前景图像 Extract foreground image using mask.
  352. 352pub fn extract_foreground(
  353. 353 img : @types.Image,
  354. 354 result : SegmentationResult,
  355. 355) -> @types.Image {
  356. 356● let w = img.width
  357. 357 let h = img.height
  358. 358 let ch = img.channels
  359. 359 let data : Array[Byte] = []
  360. 360 for y in 0..<h {
  361. 361● for x in 0..<w {
  362. 362● let mask_idx = y * w + x
  363. 363● let is_fg = if mask_idx < result.foreground_mask.length() {
  364. 364● result.foreground_mask[mask_idx]
  365. 365 } else {
  366. 366○ false
  367. 367 }
  368. 368 for c in 0..<ch {
  369. 369● if is_fg {
  370. 370● data.push(img.data[(y * w + x) * ch + c])
  371. 371 } else {
  372. 372● data.push((0 : Byte))
  373. 373 }
  374. 374 }
  375. 375 }
  376. 376 }
  377. 377● { width: w, height: h, channels: ch, data: Bytes::from_array(data), }
  378. 378}