MogensR commited on
Commit
94dcf70
·
1 Parent(s): db9de0d

Update video_processor.py

Browse files
Files changed (1) hide show
  1. video_processor.py +599 -58
video_processor.py CHANGED
@@ -1,6 +1,7 @@
1
  """
2
- Core Video Processing Module
3
- Handles the main video processing pipeline, frame processing, and background replacement
 
4
  """
5
 
6
  import os
@@ -9,7 +10,7 @@
9
  import time
10
  import logging
11
  import threading
12
- from typing import Optional, Tuple, Dict, Any, Callable
13
  from pathlib import Path
14
 
15
  # Import modular components
@@ -28,11 +29,21 @@
28
  validate_video_file
29
  )
30
 
 
 
 
 
 
 
 
 
 
 
31
  logger = logging.getLogger(__name__)
32
 
33
  class CoreVideoProcessor:
34
  """
35
- Core video processing pipeline for background replacement
36
  """
37
 
38
  def __init__(self, sam2_predictor: Any, matanyone_model: Any,
@@ -47,6 +58,12 @@ def __init__(self, sam2_predictor: Any, matanyone_model: Any,
47
  self.last_refined_mask = None
48
  self.frame_cache = {}
49
 
 
 
 
 
 
 
50
  # Statistics
51
  self.stats = {
52
  'videos_processed': 0,
@@ -57,7 +74,10 @@ def __init__(self, sam2_predictor: Any, matanyone_model: Any,
57
  'successful_frames': 0,
58
  'cache_hits': 0,
59
  'segmentation_errors': 0,
60
- 'refinement_errors': 0
 
 
 
61
  }
62
 
63
  # Quality settings based on config
@@ -66,6 +86,11 @@ def __init__(self, sam2_predictor: Any, matanyone_model: Any,
66
  logger.info("CoreVideoProcessor initialized")
67
  logger.info(f"Quality preset: {config.quality_preset}")
68
  logger.info(f"Quality settings: {self.quality_settings}")
 
 
 
 
 
69
 
70
  def process_video(
71
  self,
@@ -78,19 +103,7 @@ def process_video(
78
  preview_greenscreen: bool = False
79
  ) -> Tuple[Optional[str], str]:
80
  """
81
- Process video with background replacement
82
-
83
- Args:
84
- video_path: Input video path
85
- background_choice: Background type or name
86
- custom_background_path: Path to custom background (if applicable)
87
- progress_callback: Progress update callback
88
- cancel_event: Event to cancel processing
89
- preview_mask: Generate mask preview instead of final output
90
- preview_greenscreen: Generate greenscreen preview
91
-
92
- Returns:
93
- Tuple of (output_path, status_message)
94
  """
95
  if self.processing_active:
96
  return None, "Processing already in progress"
@@ -98,6 +111,9 @@ def process_video(
98
  self.processing_active = True
99
  start_time = time.time()
100
 
 
 
 
101
  try:
102
  # Validate input video
103
  is_valid, validation_msg = validate_video_file(video_path)
@@ -140,8 +156,8 @@ def process_video(
140
  cap.release()
141
  return None, "Could not create output video writer"
142
 
143
- # Process video frames
144
- result = self._process_video_frames(
145
  cap, out, background, video_info,
146
  progress_callback, cancel_event,
147
  preview_mask, preview_greenscreen
@@ -161,6 +177,8 @@ def process_video(
161
  f"Processed: {result['successful_frames']}/{result['total_frames']} frames\n"
162
  f"Time: {processing_time:.1f}s\n"
163
  f"Average FPS: {result['total_frames'] / processing_time:.1f}\n"
 
 
164
  f"Background: {background_choice}"
165
  )
166
 
@@ -180,6 +198,17 @@ def process_video(
180
  finally:
181
  self.processing_active = False
182
 
 
 
 
 
 
 
 
 
 
 
 
183
  def _get_video_info(self, cap: cv2.VideoCapture) -> Dict[str, Any]:
184
  """Extract comprehensive video information"""
185
  return {
@@ -232,7 +261,7 @@ def _create_video_writer(self, output_path: str,
232
  logger.error(f"Error creating video writer: {e}")
233
  return None
234
 
235
- def _process_video_frames(
236
  self,
237
  cap: cv2.VideoCapture,
238
  out: cv2.VideoWriter,
@@ -243,7 +272,7 @@ def _process_video_frames(
243
  preview_mask: bool,
244
  preview_greenscreen: bool
245
  ) -> Dict[str, Any]:
246
- """Process all video frames"""
247
 
248
  # Initialize progress tracking
249
  prog_tracker = progress_tracker.ProgressTracker(
@@ -256,12 +285,11 @@ def _process_video_frames(
256
  successful_frames = 0
257
  failed_frames = 0
258
 
259
- # Reset mask cache
260
- self.last_refined_mask = None
261
- self.frame_cache.clear()
262
 
263
  try:
264
- prog_tracker.set_stage("Processing frames")
265
 
266
  while True:
267
  # Check for cancellation
@@ -281,13 +309,19 @@ def _process_video_frames(
281
 
282
  try:
283
  # Update progress
284
- prog_tracker.update(frame_count, "Processing frame")
285
 
286
- # Process frame
287
- processed_frame = self._process_single_frame(
288
- frame, background, frame_count,
289
- preview_mask, preview_greenscreen
290
- )
 
 
 
 
 
 
291
 
292
  # Write processed frame
293
  out.write(processed_frame)
@@ -337,7 +371,7 @@ def _process_video_frames(
337
  'failed_frames': failed_frames
338
  }
339
 
340
- def _process_single_frame(
341
  self,
342
  frame: np.ndarray,
343
  background: np.ndarray,
@@ -345,7 +379,459 @@ def _process_single_frame(
345
  preview_mask: bool,
346
  preview_greenscreen: bool
347
  ) -> np.ndarray:
348
- """Process a single video frame"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
  try:
351
  # Person segmentation
@@ -353,15 +839,15 @@ def _process_single_frame(
353
 
354
  # Mask refinement (keyframe-based for performance)
355
  if self._should_refine_mask(frame_number):
356
- refined_mask = self._refine_mask(frame, mask, frame_number)
357
  self.last_refined_mask = refined_mask.copy()
358
  else:
359
  # Use temporal consistency with previous refined mask
360
- refined_mask = self._apply_temporal_consistency(mask, frame_number)
361
 
362
  # Generate output based on mode
363
  if preview_mask:
364
- return self._create_mask_preview(frame, refined_mask)
365
  elif preview_greenscreen:
366
  return self._create_greenscreen_preview(frame, refined_mask)
367
  else:
@@ -379,12 +865,35 @@ def _segment_person(self, frame: np.ndarray, frame_number: int) -> np.ndarray:
379
  if mask is None or mask.size == 0:
380
  raise exceptions.SegmentationError(frame_number, "Segmentation returned empty mask")
381
 
 
 
 
 
 
382
  return mask
383
 
384
  except Exception as e:
385
  self.stats['segmentation_errors'] += 1
386
  raise exceptions.SegmentationError(frame_number, f"Segmentation failed: {str(e)}")
387
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  def _should_refine_mask(self, frame_number: int) -> bool:
389
  """Determine if mask should be refined for this frame"""
390
  # Refine on keyframes or if no previous refined mask exists
@@ -394,8 +903,8 @@ def _should_refine_mask(self, frame_number: int) -> bool:
394
  not self.quality_settings.get('temporal_consistency', True)
395
  )
396
 
397
- def _refine_mask(self, frame: np.ndarray, mask: np.ndarray, frame_number: int) -> np.ndarray:
398
- """Refine mask using MatAnyone or fallback methods"""
399
  try:
400
  if self.matanyone_model is not None and self.quality_settings.get('edge_refinement', True):
401
  refined_mask = refine_mask_hq(frame, mask, self.matanyone_model)
@@ -412,7 +921,7 @@ def _refine_mask(self, frame: np.ndarray, mask: np.ndarray, frame_number: int) -
412
  return mask
413
 
414
  def _fallback_mask_refinement(self, mask: np.ndarray) -> np.ndarray:
415
- """Fallback mask refinement using basic OpenCV operations"""
416
  try:
417
  # Morphological operations to clean up mask
418
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
@@ -428,8 +937,29 @@ def _fallback_mask_refinement(self, mask: np.ndarray) -> np.ndarray:
428
  logger.warning(f"Fallback mask refinement failed: {e}")
429
  return mask
430
 
431
- def _apply_temporal_consistency(self, current_mask: np.ndarray, frame_number: int) -> np.ndarray:
432
- """Apply temporal consistency using previous refined mask"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
  if self.last_refined_mask is None or not self.quality_settings.get('temporal_consistency', True):
434
  return current_mask
435
 
@@ -457,8 +987,8 @@ def _apply_temporal_consistency(self, current_mask: np.ndarray, frame_number: in
457
  logger.warning(f"Temporal consistency application failed: {e}")
458
  return current_mask
459
 
460
- def _create_mask_preview(self, frame: np.ndarray, mask: np.ndarray) -> np.ndarray:
461
- """Create mask visualization preview"""
462
  try:
463
  # Create colored mask overlay
464
  mask_colored = np.zeros_like(frame)
@@ -510,18 +1040,7 @@ def prepare_background(
510
  width: int,
511
  height: int
512
  ) -> Optional[np.ndarray]:
513
- """
514
- Prepare background image for processing
515
-
516
- Args:
517
- background_choice: Background type or name
518
- custom_background_path: Path to custom background
519
- width: Target width
520
- height: Target height
521
-
522
- Returns:
523
- Prepared background image or None if failed
524
- """
525
  try:
526
  if background_choice == "custom" and custom_background_path:
527
  if not os.path.exists(custom_background_path):
@@ -576,7 +1095,7 @@ def _update_processing_stats(self, video_info: Dict[str, Any],
576
 
577
  def get_processing_capabilities(self) -> Dict[str, Any]:
578
  """Get current processing capabilities"""
579
- return {
580
  'sam2_available': self.sam2_predictor is not None,
581
  'matanyone_available': self.matanyone_model is not None,
582
  'quality_preset': self.config.quality_preset,
@@ -587,10 +1106,21 @@ def get_processing_capabilities(self) -> Dict[str, Any]:
587
  'supported_formats': ['.mp4', '.avi', '.mov', '.mkv'],
588
  'memory_limit_gb': self.memory_manager.memory_limit_gb
589
  }
 
 
 
 
 
 
 
 
 
 
 
590
 
591
  def get_status(self) -> Dict[str, Any]:
592
  """Get current processor status"""
593
- return {
594
  'processing_active': self.processing_active,
595
  'models_available': {
596
  'sam2': self.sam2_predictor is not None,
@@ -602,6 +1132,16 @@ def get_status(self) -> Dict[str, Any]:
602
  'memory_usage': self.memory_manager.get_memory_usage(),
603
  'capabilities': self.get_processing_capabilities()
604
  }
 
 
 
 
 
 
 
 
 
 
605
 
606
  def optimize_for_video(self, video_info: Dict[str, Any]) -> Dict[str, Any]:
607
  """Optimize settings for specific video characteristics"""
@@ -656,6 +1196,7 @@ def reset_cache(self):
656
  self.frame_cache.clear()
657
  self.last_refined_mask = None
658
  self.stats['cache_hits'] = 0
 
659
  logger.debug("Frame cache and temporal state reset")
660
 
661
  def cleanup(self):
 
1
  """
2
+ Core Video Processing Module - Enhanced with Temporal Consistency
3
+ VERSION: 2.0-temporal-enhanced
4
+ ROLLBACK: Set USE_TEMPORAL_ENHANCEMENT = False to revert to original behavior
5
  """
6
 
7
  import os
 
10
  import time
11
  import logging
12
  import threading
13
+ from typing import Optional, Tuple, Dict, Any, Callable, List
14
  from pathlib import Path
15
 
16
  # Import modular components
 
29
  validate_video_file
30
  )
31
 
32
+ # ============================================================================
33
+ # VERSION CONTROL AND FEATURE FLAGS - EASY ROLLBACK
34
+ # ============================================================================
35
+
36
+ # ROLLBACK CONTROL: Set to False to use original functions
37
+ USE_TEMPORAL_ENHANCEMENT = True
38
+ USE_HAIR_DETECTION = True
39
+ USE_OPTICAL_FLOW_TRACKING = True
40
+ USE_ADAPTIVE_REFINEMENT = True
41
+
42
  logger = logging.getLogger(__name__)
43
 
44
  class CoreVideoProcessor:
45
  """
46
+ ENHANCED: Core video processing pipeline with temporal consistency and fine-detail handling
47
  """
48
 
49
  def __init__(self, sam2_predictor: Any, matanyone_model: Any,
 
58
  self.last_refined_mask = None
59
  self.frame_cache = {}
60
 
61
+ # ENHANCED: Temporal consistency state
62
+ self.mask_history = [] # Store recent masks for temporal smoothing
63
+ self.optical_flow_data = None # Previous frame for optical flow
64
+ self.hair_regions_cache = {} # Cache detected hair regions
65
+ self.quality_scores_history = [] # Track quality over time
66
+
67
  # Statistics
68
  self.stats = {
69
  'videos_processed': 0,
 
74
  'successful_frames': 0,
75
  'cache_hits': 0,
76
  'segmentation_errors': 0,
77
+ 'refinement_errors': 0,
78
+ 'temporal_corrections': 0, # NEW: Track temporal fixes
79
+ 'hair_detections': 0, # NEW: Track hair detection success
80
+ 'flow_tracking_failures': 0 # NEW: Track optical flow issues
81
  }
82
 
83
  # Quality settings based on config
 
86
  logger.info("CoreVideoProcessor initialized")
87
  logger.info(f"Quality preset: {config.quality_preset}")
88
  logger.info(f"Quality settings: {self.quality_settings}")
89
+
90
+ if USE_TEMPORAL_ENHANCEMENT:
91
+ logger.info("ENHANCED: Temporal consistency enabled")
92
+ if USE_HAIR_DETECTION:
93
+ logger.info("ENHANCED: Hair detection enabled")
94
 
95
  def process_video(
96
  self,
 
103
  preview_greenscreen: bool = False
104
  ) -> Tuple[Optional[str], str]:
105
  """
106
+ ENHANCED: Process video with temporal consistency and fine-detail handling
 
 
 
 
 
 
 
 
 
 
 
 
107
  """
108
  if self.processing_active:
109
  return None, "Processing already in progress"
 
111
  self.processing_active = True
112
  start_time = time.time()
113
 
114
+ # ENHANCED: Reset temporal state for new video
115
+ self._reset_temporal_state()
116
+
117
  try:
118
  # Validate input video
119
  is_valid, validation_msg = validate_video_file(video_path)
 
156
  cap.release()
157
  return None, "Could not create output video writer"
158
 
159
+ # ENHANCED: Process video frames with temporal consistency
160
+ result = self._process_video_frames_enhanced(
161
  cap, out, background, video_info,
162
  progress_callback, cancel_event,
163
  preview_mask, preview_greenscreen
 
177
  f"Processed: {result['successful_frames']}/{result['total_frames']} frames\n"
178
  f"Time: {processing_time:.1f}s\n"
179
  f"Average FPS: {result['total_frames'] / processing_time:.1f}\n"
180
+ f"Temporal corrections: {self.stats['temporal_corrections']}\n"
181
+ f"Hair detections: {self.stats['hair_detections']}\n"
182
  f"Background: {background_choice}"
183
  )
184
 
 
198
  finally:
199
  self.processing_active = False
200
 
201
+ def _reset_temporal_state(self):
202
+ """ENHANCED: Reset temporal consistency state"""
203
+ self.mask_history.clear()
204
+ self.optical_flow_data = None
205
+ self.hair_regions_cache.clear()
206
+ self.quality_scores_history.clear()
207
+ self.last_refined_mask = None
208
+ self.stats['temporal_corrections'] = 0
209
+ self.stats['hair_detections'] = 0
210
+ self.stats['flow_tracking_failures'] = 0
211
+
212
  def _get_video_info(self, cap: cv2.VideoCapture) -> Dict[str, Any]:
213
  """Extract comprehensive video information"""
214
  return {
 
261
  logger.error(f"Error creating video writer: {e}")
262
  return None
263
 
264
+ def _process_video_frames_enhanced(
265
  self,
266
  cap: cv2.VideoCapture,
267
  out: cv2.VideoWriter,
 
272
  preview_mask: bool,
273
  preview_greenscreen: bool
274
  ) -> Dict[str, Any]:
275
+ """ENHANCED: Process all video frames with temporal consistency"""
276
 
277
  # Initialize progress tracking
278
  prog_tracker = progress_tracker.ProgressTracker(
 
285
  successful_frames = 0
286
  failed_frames = 0
287
 
288
+ # Reset enhanced state
289
+ self._reset_temporal_state()
 
290
 
291
  try:
292
+ prog_tracker.set_stage("Processing frames with temporal enhancement")
293
 
294
  while True:
295
  # Check for cancellation
 
309
 
310
  try:
311
  # Update progress
312
+ prog_tracker.update(frame_count, "Processing frame with temporal consistency")
313
 
314
+ # ENHANCED: Process frame with temporal consistency
315
+ if USE_TEMPORAL_ENHANCEMENT:
316
+ processed_frame = self._process_single_frame_enhanced(
317
+ frame, background, frame_count,
318
+ preview_mask, preview_greenscreen
319
+ )
320
+ else:
321
+ processed_frame = self._process_single_frame_original(
322
+ frame, background, frame_count,
323
+ preview_mask, preview_greenscreen
324
+ )
325
 
326
  # Write processed frame
327
  out.write(processed_frame)
 
371
  'failed_frames': failed_frames
372
  }
373
 
374
+ def _process_single_frame_enhanced(
375
  self,
376
  frame: np.ndarray,
377
  background: np.ndarray,
 
379
  preview_mask: bool,
380
  preview_greenscreen: bool
381
  ) -> np.ndarray:
382
+ """ENHANCED: Process a single video frame with temporal consistency"""
383
+
384
+ try:
385
+ # Person segmentation
386
+ mask = self._segment_person_enhanced(frame, frame_number)
387
+
388
+ # ENHANCED: Detect hair and fine details
389
+ if USE_HAIR_DETECTION:
390
+ hair_regions = self._detect_hair_regions(frame, mask, frame_number)
391
+ else:
392
+ hair_regions = None
393
+
394
+ # ENHANCED: Apply temporal consistency
395
+ if USE_TEMPORAL_ENHANCEMENT and len(self.mask_history) > 0:
396
+ mask = self._apply_temporal_consistency_enhanced(frame, mask, frame_number)
397
+
398
+ # ENHANCED: Adaptive mask refinement based on frame content
399
+ if USE_ADAPTIVE_REFINEMENT:
400
+ refined_mask = self._adaptive_mask_refinement(frame, mask, frame_number, hair_regions)
401
+ else:
402
+ refined_mask = self._refine_mask_original(frame, mask, frame_number)
403
+
404
+ # Store mask in history for temporal consistency
405
+ self._update_mask_history(refined_mask)
406
+
407
+ # Generate output based on mode
408
+ if preview_mask:
409
+ return self._create_mask_preview_enhanced(frame, refined_mask, hair_regions)
410
+ elif preview_greenscreen:
411
+ return self._create_greenscreen_preview(frame, refined_mask)
412
+ else:
413
+ return self._replace_background_enhanced(frame, refined_mask, background, hair_regions)
414
+
415
+ except Exception as e:
416
+ logger.warning(f"Enhanced single frame processing failed: {e}")
417
+ # Fallback to original processing
418
+ return self._process_single_frame_original(frame, background, frame_number, preview_mask, preview_greenscreen)
419
+
420
+ def _detect_hair_regions(self, frame: np.ndarray, mask: np.ndarray, frame_number: int) -> Optional[np.ndarray]:
421
+ """ENHANCED: Detect hair and fine detail regions automatically"""
422
+ try:
423
+ # Check cache first
424
+ if frame_number in self.hair_regions_cache:
425
+ self.stats['cache_hits'] += 1
426
+ return self.hair_regions_cache[frame_number]
427
+
428
+ # Convert frame to different color spaces for better hair detection
429
+ hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
430
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
431
+
432
+ # Method 1: Texture-based hair detection
433
+ # Hair typically has high frequency texture
434
+ laplacian = cv2.Laplacian(gray, cv2.CV_64F)
435
+ texture_strength = np.abs(laplacian)
436
+
437
+ # Method 2: Color-based hair detection
438
+ # Hair is typically in darker hue ranges
439
+ hair_hue_mask = ((hsv[:,:,0] >= 0) & (hsv[:,:,0] <= 30)) | \
440
+ ((hsv[:,:,0] >= 150) & (hsv[:,:,0] <= 180))
441
+ hair_value_mask = hsv[:,:,2] < 100 # Darker regions
442
+
443
+ # Combine texture and color information
444
+ hair_probability = np.zeros_like(gray, dtype=np.float32)
445
+
446
+ # High texture regions
447
+ texture_norm = (texture_strength - texture_strength.min()) / (texture_strength.max() - texture_strength.min() + 1e-8)
448
+ hair_probability += texture_norm * 0.6
449
+
450
+ # Color-based probability
451
+ color_prob = (hair_hue_mask.astype(np.float32) * hair_value_mask.astype(np.float32))
452
+ hair_probability += color_prob * 0.4
453
+
454
+ # Only consider regions near the mask boundary (where hair typically is)
455
+ mask_boundary = self._get_mask_boundary_region(mask, boundary_width=20)
456
+ hair_probability *= mask_boundary
457
+
458
+ # Threshold to get hair regions
459
+ hair_threshold = np.percentile(hair_probability[hair_probability > 0], 75)
460
+ hair_regions = (hair_probability > hair_threshold).astype(np.uint8)
461
+
462
+ # Clean up hair regions
463
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
464
+ hair_regions = cv2.morphologyEx(hair_regions, cv2.MORPH_CLOSE, kernel)
465
+
466
+ # Cache the result
467
+ self.hair_regions_cache[frame_number] = hair_regions
468
+
469
+ # Update stats if hair was detected
470
+ if np.any(hair_regions):
471
+ self.stats['hair_detections'] += 1
472
+ logger.debug(f"Hair regions detected in frame {frame_number}")
473
+
474
+ return hair_regions
475
+
476
+ except Exception as e:
477
+ logger.warning(f"Hair detection failed for frame {frame_number}: {e}")
478
+ return None
479
+
480
+ def _get_mask_boundary_region(self, mask: np.ndarray, boundary_width: int = 20) -> np.ndarray:
481
+ """Get region around mask boundary where hair/fine details are likely"""
482
+ try:
483
+ # Create dilated and eroded versions of mask
484
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (boundary_width, boundary_width))
485
+ dilated = cv2.dilate(mask, kernel, iterations=1)
486
+ eroded = cv2.erode(mask, kernel, iterations=1)
487
+
488
+ # Boundary region is dilated minus eroded
489
+ boundary_region = ((dilated > 0) & (eroded == 0)).astype(np.float32)
490
+
491
+ return boundary_region
492
+
493
+ except Exception as e:
494
+ logger.warning(f"Boundary region detection failed: {e}")
495
+ return np.ones_like(mask, dtype=np.float32)
496
+
497
+ def _apply_temporal_consistency_enhanced(self, frame: np.ndarray, current_mask: np.ndarray, frame_number: int) -> np.ndarray:
498
+ """ENHANCED: Apply temporal consistency using optical flow and history"""
499
+ try:
500
+ if len(self.mask_history) == 0:
501
+ return current_mask
502
+
503
+ previous_mask = self.mask_history[-1]
504
+
505
+ # Method 1: Optical flow-based consistency
506
+ if USE_OPTICAL_FLOW_TRACKING and self.optical_flow_data is not None:
507
+ try:
508
+ flow_corrected_mask = self._apply_optical_flow_consistency(
509
+ frame, current_mask, previous_mask
510
+ )
511
+
512
+ # Blend flow-corrected with current mask
513
+ alpha = 0.7 # Weight for current mask
514
+ beta = 0.3 # Weight for flow-corrected mask
515
+
516
+ blended_mask = cv2.addWeighted(
517
+ current_mask.astype(np.float32), alpha,
518
+ flow_corrected_mask.astype(np.float32), beta, 0
519
+ ).astype(np.uint8)
520
+
521
+ self.stats['temporal_corrections'] += 1
522
+
523
+ except Exception as e:
524
+ logger.debug(f"Optical flow consistency failed: {e}")
525
+ self.stats['flow_tracking_failures'] += 1
526
+ blended_mask = current_mask
527
+ else:
528
+ blended_mask = current_mask
529
+
530
+ # Method 2: Multi-frame temporal smoothing
531
+ if len(self.mask_history) >= 3:
532
+ # Use weighted average of recent masks
533
+ weights = [0.5, 0.3, 0.2] # Current, previous, before previous
534
+ masks_to_blend = [blended_mask] + self.mask_history[-2:]
535
+
536
+ temporal_mask = np.zeros_like(blended_mask, dtype=np.float32)
537
+ for mask, weight in zip(masks_to_blend, weights):
538
+ temporal_mask += mask.astype(np.float32) * weight
539
+
540
+ blended_mask = np.clip(temporal_mask, 0, 255).astype(np.uint8)
541
+
542
+ # Method 3: Edge-aware temporal filtering
543
+ blended_mask = self._temporal_edge_filtering(frame, blended_mask, current_mask)
544
+
545
+ return blended_mask
546
+
547
+ except Exception as e:
548
+ logger.warning(f"Temporal consistency failed: {e}")
549
+ return current_mask
550
+
551
+ def _apply_optical_flow_consistency(self, current_frame: np.ndarray,
552
+ current_mask: np.ndarray, previous_mask: np.ndarray) -> np.ndarray:
553
+ """Apply optical flow to warp previous mask to current frame"""
554
+ try:
555
+ # Convert frames to grayscale for optical flow
556
+ current_gray = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
557
+ previous_gray = self.optical_flow_data
558
+
559
+ # Calculate dense optical flow
560
+ flow = cv2.calcOpticalFlowPyrLK(previous_gray, current_gray, None, None)
561
+
562
+ # Warp previous mask using optical flow
563
+ h, w = previous_mask.shape
564
+ flow_map = np.zeros((h, w, 2), dtype=np.float32)
565
+
566
+ # Create flow field
567
+ y_coords, x_coords = np.mgrid[0:h, 0:w]
568
+ flow_map[:, :, 0] = x_coords + flow[0] if flow[0] is not None else x_coords
569
+ flow_map[:, :, 1] = y_coords + flow[1] if flow[1] is not None else y_coords
570
+
571
+ # Warp previous mask
572
+ warped_mask = cv2.remap(previous_mask, flow_map, None, cv2.INTER_LINEAR)
573
+
574
+ return warped_mask
575
+
576
+ except Exception as e:
577
+ logger.debug(f"Optical flow warping failed: {e}")
578
+ return previous_mask
579
+
580
+ def _temporal_edge_filtering(self, frame: np.ndarray, blended_mask: np.ndarray, current_mask: np.ndarray) -> np.ndarray:
581
+ """Apply edge-aware temporal filtering"""
582
+ try:
583
+ # Detect edges in current frame
584
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
585
+ edges = cv2.Canny(gray, 50, 150)
586
+
587
+ # In edge regions, favor the current mask (more responsive)
588
+ # In smooth regions, favor the blended mask (more stable)
589
+ edge_weight = cv2.GaussianBlur(edges.astype(np.float32), (5, 5), 1.0) / 255.0
590
+
591
+ filtered_mask = (current_mask.astype(np.float32) * edge_weight +
592
+ blended_mask.astype(np.float32) * (1 - edge_weight))
593
+
594
+ return np.clip(filtered_mask, 0, 255).astype(np.uint8)
595
+
596
+ except Exception as e:
597
+ logger.warning(f"Temporal edge filtering failed: {e}")
598
+ return blended_mask
599
+
600
+ def _adaptive_mask_refinement(self, frame: np.ndarray, mask: np.ndarray,
601
+ frame_number: int, hair_regions: Optional[np.ndarray]) -> np.ndarray:
602
+ """ENHANCED: Adaptive mask refinement based on content analysis"""
603
+ try:
604
+ # Determine refinement strategy based on frame content
605
+ refinement_needed = self._assess_refinement_needs(frame, mask, hair_regions)
606
+
607
+ if refinement_needed['hair_refinement'] and hair_regions is not None:
608
+ # Special handling for hair regions
609
+ mask = self._refine_hair_regions(frame, mask, hair_regions)
610
+
611
+ if refinement_needed['edge_refinement']:
612
+ # Enhanced edge refinement
613
+ mask = self._enhanced_edge_refinement(frame, mask)
614
+
615
+ if refinement_needed['temporal_refinement']:
616
+ # Apply temporal-aware refinement
617
+ mask = self._temporal_aware_refinement(frame, mask, frame_number)
618
+
619
+ # Standard refinement if needed
620
+ if self._should_refine_mask(frame_number):
621
+ if self.matanyone_model is not None and self.quality_settings.get('edge_refinement', True):
622
+ mask = refine_mask_hq(frame, mask, self.matanyone_model)
623
+ else:
624
+ mask = self._fallback_mask_refinement_enhanced(mask)
625
+
626
+ return mask
627
+
628
+ except Exception as e:
629
+ logger.warning(f"Adaptive mask refinement failed: {e}")
630
+ return self._refine_mask_original(frame, mask, frame_number)
631
+
632
+ def _assess_refinement_needs(self, frame: np.ndarray, mask: np.ndarray,
633
+ hair_regions: Optional[np.ndarray]) -> Dict[str, bool]:
634
+ """Assess what type of refinement is needed for this frame"""
635
+ try:
636
+ needs = {
637
+ 'hair_refinement': False,
638
+ 'edge_refinement': False,
639
+ 'temporal_refinement': False
640
+ }
641
+
642
+ # Check if hair refinement is needed
643
+ if hair_regions is not None and np.any(hair_regions):
644
+ needs['hair_refinement'] = True
645
+
646
+ # Check edge quality
647
+ edges = cv2.Canny(mask, 50, 150)
648
+ edge_density = np.sum(edges > 0) / (mask.shape[0] * mask.shape[1])
649
+ if edge_density > 0.1: # High edge density suggests rough boundaries
650
+ needs['edge_refinement'] = True
651
+
652
+ # Check temporal consistency needs
653
+ if len(self.mask_history) > 0:
654
+ prev_mask = self.mask_history[-1]
655
+ diff = cv2.absdiff(mask, prev_mask)
656
+ change_ratio = np.sum(diff > 50) / (mask.shape[0] * mask.shape[1])
657
+ if change_ratio > 0.15: # High change suggests temporal inconsistency
658
+ needs['temporal_refinement'] = True
659
+
660
+ return needs
661
+
662
+ except Exception as e:
663
+ logger.warning(f"Refinement assessment failed: {e}")
664
+ return {'hair_refinement': False, 'edge_refinement': True, 'temporal_refinement': False}
665
+
666
+ def _refine_hair_regions(self, frame: np.ndarray, mask: np.ndarray, hair_regions: np.ndarray) -> np.ndarray:
667
+ """Special refinement for hair and fine detail regions"""
668
+ try:
669
+ # Create a more aggressive mask for hair regions
670
+ hair_mask = hair_regions > 0
671
+
672
+ # Use different thresholding for hair areas
673
+ refined_mask = mask.copy()
674
+
675
+ # In hair regions, use lower threshold (include more pixels)
676
+ hair_area_values = mask[hair_mask]
677
+ if len(hair_area_values) > 0:
678
+ hair_threshold = max(100, np.percentile(hair_area_values, 25)) # Lower threshold for hair
679
+ refined_mask[hair_mask] = np.where(mask[hair_mask] > hair_threshold, 255, 0)
680
+
681
+ # Apply morphological closing to connect hair strands
682
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
683
+ refined_mask = cv2.morphologyEx(refined_mask, cv2.MORPH_CLOSE, kernel)
684
+
685
+ return refined_mask
686
+
687
+ except Exception as e:
688
+ logger.warning(f"Hair region refinement failed: {e}")
689
+ return mask
690
+
691
+ def _enhanced_edge_refinement(self, frame: np.ndarray, mask: np.ndarray) -> np.ndarray:
692
+ """Enhanced edge refinement using image gradients"""
693
+ try:
694
+ # Use bilateral filter to preserve edges while smoothing
695
+ refined = cv2.bilateralFilter(mask, 9, 75, 75)
696
+
697
+ # Edge-guided smoothing
698
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
699
+ edges = cv2.Canny(gray, 50, 150)
700
+
701
+ # In edge areas, preserve original mask more
702
+ edge_weight = cv2.GaussianBlur(edges.astype(np.float32), (3, 3), 1.0) / 255.0
703
+ edge_weight = np.clip(edge_weight * 2, 0, 1) # Amplify edge influence
704
+
705
+ final_mask = (mask.astype(np.float32) * edge_weight +
706
+ refined.astype(np.float32) * (1 - edge_weight))
707
+
708
+ return np.clip(final_mask, 0, 255).astype(np.uint8)
709
+
710
+ except Exception as e:
711
+ logger.warning(f"Enhanced edge refinement failed: {e}")
712
+ return mask
713
+
714
+ def _temporal_aware_refinement(self, frame: np.ndarray, mask: np.ndarray, frame_number: int) -> np.ndarray:
715
+ """Temporal-aware refinement considering motion and stability"""
716
+ try:
717
+ if len(self.mask_history) == 0:
718
+ return mask
719
+
720
+ # Calculate motion between frames
721
+ if self.optical_flow_data is not None:
722
+ current_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
723
+ motion_magnitude = cv2.absdiff(current_gray, self.optical_flow_data)
724
+ motion_mask = motion_magnitude > 10 # Areas with motion
725
+
726
+ # In high-motion areas, trust current mask more
727
+ # In low-motion areas, use temporal smoothing
728
+ prev_mask = self.mask_history[-1]
729
+
730
+ motion_weight = cv2.GaussianBlur(motion_mask.astype(np.float32), (5, 5), 1.0)
731
+ motion_weight = np.clip(motion_weight, 0.3, 1.0) # Don't completely ignore temporal info
732
+
733
+ temporal_mask = (mask.astype(np.float32) * motion_weight +
734
+ prev_mask.astype(np.float32) * (1 - motion_weight))
735
+
736
+ return np.clip(temporal_mask, 0, 255).astype(np.uint8)
737
+
738
+ return mask
739
+
740
+ except Exception as e:
741
+ logger.warning(f"Temporal-aware refinement failed: {e}")
742
+ return mask
743
+
744
+ def _update_mask_history(self, mask: np.ndarray):
745
+ """Update mask history for temporal consistency"""
746
+ self.mask_history.append(mask.copy())
747
+
748
+ # Keep only recent history (limit memory usage)
749
+ max_history = 5
750
+ if len(self.mask_history) > max_history:
751
+ self.mask_history.pop(0)
752
+
753
+ def _create_mask_preview_enhanced(self, frame: np.ndarray, mask: np.ndarray,
754
+ hair_regions: Optional[np.ndarray]) -> np.ndarray:
755
+ """ENHANCED: Create mask visualization with hair regions highlighted"""
756
+ try:
757
+ # Create colored mask overlay
758
+ mask_colored = np.zeros_like(frame)
759
+ mask_colored[:, :, 1] = mask # Green channel for person
760
+
761
+ # Highlight hair regions in blue if available
762
+ if hair_regions is not None:
763
+ mask_colored[:, :, 2] = np.maximum(mask_colored[:, :, 2], hair_regions * 255)
764
+
765
+ # Blend with original frame
766
+ alpha = 0.6
767
+ preview = cv2.addWeighted(frame, 1-alpha, mask_colored, alpha, 0)
768
+
769
+ return preview
770
+
771
+ except Exception as e:
772
+ logger.warning(f"Enhanced mask preview creation failed: {e}")
773
+ return self._create_mask_preview_original(frame, mask)
774
+
775
+ def _replace_background_enhanced(self, frame: np.ndarray, mask: np.ndarray,
776
+ background: np.ndarray, hair_regions: Optional[np.ndarray]) -> np.ndarray:
777
+ """ENHANCED: Replace background with special handling for hair regions"""
778
+ try:
779
+ # Standard background replacement
780
+ result = replace_background_hq(frame, mask, background)
781
+
782
+ # If hair regions detected, apply additional processing
783
+ if hair_regions is not None and np.any(hair_regions):
784
+ result = self._enhance_hair_compositing(frame, mask, background, hair_regions, result)
785
+
786
+ return result
787
+
788
+ except Exception as e:
789
+ logger.warning(f"Enhanced background replacement failed: {e}")
790
+ return replace_background_hq(frame, mask, background)
791
+
792
+ def _enhance_hair_compositing(self, frame: np.ndarray, mask: np.ndarray,
793
+ background: np.ndarray, hair_regions: np.ndarray,
794
+ initial_result: np.ndarray) -> np.ndarray:
795
+ """Enhanced compositing specifically for hair regions"""
796
+ try:
797
+ # In hair regions, use softer alpha blending
798
+ hair_mask = hair_regions > 0
799
+
800
+ if np.any(hair_mask):
801
+ # Create soft alpha for hair regions
802
+ hair_alpha = cv2.GaussianBlur((hair_regions * mask / 255.0).astype(np.float32), (3, 3), 1.0)
803
+ hair_alpha = np.clip(hair_alpha, 0, 1)
804
+
805
+ # Apply softer blending only in hair regions
806
+ for c in range(3):
807
+ channel_blend = (frame[:, :, c].astype(np.float32) * hair_alpha +
808
+ background[:, :, c].astype(np.float32) * (1 - hair_alpha))
809
+
810
+ initial_result[:, :, c] = np.where(
811
+ hair_mask,
812
+ np.clip(channel_blend, 0, 255).astype(np.uint8),
813
+ initial_result[:, :, c]
814
+ )
815
+
816
+ return initial_result
817
+
818
+ except Exception as e:
819
+ logger.warning(f"Hair compositing enhancement failed: {e}")
820
+ return initial_result
821
+
822
+ # ============================================================================
823
+ # ORIGINAL FUNCTIONS PRESERVED FOR ROLLBACK
824
+ # ============================================================================
825
+
826
+ def _process_single_frame_original(
827
+ self,
828
+ frame: np.ndarray,
829
+ background: np.ndarray,
830
+ frame_number: int,
831
+ preview_mask: bool,
832
+ preview_greenscreen: bool
833
+ ) -> np.ndarray:
834
+ """ORIGINAL: Process a single video frame (preserved for rollback)"""
835
 
836
  try:
837
  # Person segmentation
 
839
 
840
  # Mask refinement (keyframe-based for performance)
841
  if self._should_refine_mask(frame_number):
842
+ refined_mask = self._refine_mask_original(frame, mask, frame_number)
843
  self.last_refined_mask = refined_mask.copy()
844
  else:
845
  # Use temporal consistency with previous refined mask
846
+ refined_mask = self._apply_temporal_consistency_original(mask, frame_number)
847
 
848
  # Generate output based on mode
849
  if preview_mask:
850
+ return self._create_mask_preview_original(frame, refined_mask)
851
  elif preview_greenscreen:
852
  return self._create_greenscreen_preview(frame, refined_mask)
853
  else:
 
865
  if mask is None or mask.size == 0:
866
  raise exceptions.SegmentationError(frame_number, "Segmentation returned empty mask")
867
 
868
+ # Store current frame for optical flow (if enhanced mode enabled)
869
+ if USE_OPTICAL_FLOW_TRACKING:
870
+ current_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
871
+ self.optical_flow_data = current_gray
872
+
873
  return mask
874
 
875
  except Exception as e:
876
  self.stats['segmentation_errors'] += 1
877
  raise exceptions.SegmentationError(frame_number, f"Segmentation failed: {str(e)}")
878
 
879
+ def _segment_person_enhanced(self, frame: np.ndarray, frame_number: int) -> np.ndarray:
880
+ """ENHANCED: Perform person segmentation with improvements"""
881
+ try:
882
+ mask = segment_person_hq(frame, self.sam2_predictor)
883
+
884
+ if mask is None or mask.size == 0:
885
+ raise exceptions.SegmentationError(frame_number, "Segmentation returned empty mask")
886
+
887
+ # Store current frame for optical flow
888
+ current_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
889
+ self.optical_flow_data = current_gray
890
+
891
+ return mask
892
+
893
+ except Exception as e:
894
+ self.stats['segmentation_errors'] += 1
895
+ raise exceptions.SegmentationError(frame_number, f"Enhanced segmentation failed: {str(e)}")
896
+
897
  def _should_refine_mask(self, frame_number: int) -> bool:
898
  """Determine if mask should be refined for this frame"""
899
  # Refine on keyframes or if no previous refined mask exists
 
903
  not self.quality_settings.get('temporal_consistency', True)
904
  )
905
 
906
+ def _refine_mask_original(self, frame: np.ndarray, mask: np.ndarray, frame_number: int) -> np.ndarray:
907
+ """ORIGINAL: Refine mask using MatAnyone or fallback methods"""
908
  try:
909
  if self.matanyone_model is not None and self.quality_settings.get('edge_refinement', True):
910
  refined_mask = refine_mask_hq(frame, mask, self.matanyone_model)
 
921
  return mask
922
 
923
  def _fallback_mask_refinement(self, mask: np.ndarray) -> np.ndarray:
924
+ """ORIGINAL: Fallback mask refinement using basic OpenCV operations"""
925
  try:
926
  # Morphological operations to clean up mask
927
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
 
937
  logger.warning(f"Fallback mask refinement failed: {e}")
938
  return mask
939
 
940
+ def _fallback_mask_refinement_enhanced(self, mask: np.ndarray) -> np.ndarray:
941
+ """ENHANCED: Improved fallback mask refinement"""
942
+ try:
943
+ # More aggressive morphological operations
944
+ kernel_small = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2, 2))
945
+ kernel_large = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
946
+
947
+ # Remove small noise
948
+ refined = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_small)
949
+ # Fill gaps
950
+ refined = cv2.morphologyEx(refined, cv2.MORPH_CLOSE, kernel_large)
951
+
952
+ # Edge smoothing with bilateral filter instead of Gaussian
953
+ refined = cv2.bilateralFilter(refined, 9, 75, 75)
954
+
955
+ return refined
956
+
957
+ except Exception as e:
958
+ logger.warning(f"Enhanced fallback mask refinement failed: {e}")
959
+ return mask
960
+
961
+ def _apply_temporal_consistency_original(self, current_mask: np.ndarray, frame_number: int) -> np.ndarray:
962
+ """ORIGINAL: Apply temporal consistency using previous refined mask"""
963
  if self.last_refined_mask is None or not self.quality_settings.get('temporal_consistency', True):
964
  return current_mask
965
 
 
987
  logger.warning(f"Temporal consistency application failed: {e}")
988
  return current_mask
989
 
990
+ def _create_mask_preview_original(self, frame: np.ndarray, mask: np.ndarray) -> np.ndarray:
991
+ """ORIGINAL: Create mask visualization preview"""
992
  try:
993
  # Create colored mask overlay
994
  mask_colored = np.zeros_like(frame)
 
1040
  width: int,
1041
  height: int
1042
  ) -> Optional[np.ndarray]:
1043
+ """Prepare background image for processing (unchanged)"""
 
 
 
 
 
 
 
 
 
 
 
1044
  try:
1045
  if background_choice == "custom" and custom_background_path:
1046
  if not os.path.exists(custom_background_path):
 
1095
 
1096
  def get_processing_capabilities(self) -> Dict[str, Any]:
1097
  """Get current processing capabilities"""
1098
+ capabilities = {
1099
  'sam2_available': self.sam2_predictor is not None,
1100
  'matanyone_available': self.matanyone_model is not None,
1101
  'quality_preset': self.config.quality_preset,
 
1106
  'supported_formats': ['.mp4', '.avi', '.mov', '.mkv'],
1107
  'memory_limit_gb': self.memory_manager.memory_limit_gb
1108
  }
1109
+
1110
+ # Add enhanced capabilities
1111
+ if USE_TEMPORAL_ENHANCEMENT:
1112
+ capabilities.update({
1113
+ 'temporal_enhancement': True,
1114
+ 'hair_detection': USE_HAIR_DETECTION,
1115
+ 'optical_flow_tracking': USE_OPTICAL_FLOW_TRACKING,
1116
+ 'adaptive_refinement': USE_ADAPTIVE_REFINEMENT
1117
+ })
1118
+
1119
+ return capabilities
1120
 
1121
  def get_status(self) -> Dict[str, Any]:
1122
  """Get current processor status"""
1123
+ status = {
1124
  'processing_active': self.processing_active,
1125
  'models_available': {
1126
  'sam2': self.sam2_predictor is not None,
 
1132
  'memory_usage': self.memory_manager.get_memory_usage(),
1133
  'capabilities': self.get_processing_capabilities()
1134
  }
1135
+
1136
+ # Add enhanced status
1137
+ if USE_TEMPORAL_ENHANCEMENT:
1138
+ status.update({
1139
+ 'mask_history_length': len(self.mask_history),
1140
+ 'hair_cache_size': len(self.hair_regions_cache),
1141
+ 'optical_flow_active': self.optical_flow_data is not None
1142
+ })
1143
+
1144
+ return status
1145
 
1146
  def optimize_for_video(self, video_info: Dict[str, Any]) -> Dict[str, Any]:
1147
  """Optimize settings for specific video characteristics"""
 
1196
  self.frame_cache.clear()
1197
  self.last_refined_mask = None
1198
  self.stats['cache_hits'] = 0
1199
+ self._reset_temporal_state()
1200
  logger.debug("Frame cache and temporal state reset")
1201
 
1202
  def cleanup(self):