Spaces:
Running
Running
Anish commited on
Commit ·
f49287c
1
Parent(s): 739e45e
[Feature Added] > motion detector. This detects motion using Farneback Flow, which tracks motion using mathematical equations. If motion is violent and closer to 1.0 - It is AI, If motion is smooth and lower - it is Natural.
Browse files
backend/app/ai/video/motion_detector.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import logging
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
def compute_motion_anomaly(prev_frame: np.ndarray, curr_frame: np.ndarray) -> Optional[float]:
|
| 9 |
+
try:
|
| 10 |
+
if prev_frame is None or curr_frame is None:
|
| 11 |
+
return None
|
| 12 |
+
|
| 13 |
+
if prev_frame.shape != curr_frame.shape:
|
| 14 |
+
logger.warning("Motion Anomaly: Frame resolution mismatch. Cannot compute flow.")
|
| 15 |
+
return None
|
| 16 |
+
|
| 17 |
+
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)
|
| 18 |
+
curr_gray = cv2.cvtColor(curr_frame, cv2.COLOR_BGR2GRAY)
|
| 19 |
+
|
| 20 |
+
scale_target = (320, 240)
|
| 21 |
+
prev_small = cv2.resize(prev_gray, scale_target, interpolation=cv2.INTER_AREA)
|
| 22 |
+
curr_small = cv2.resize(curr_gray, scale_target, interpolation=cv2.INTER_AREA)
|
| 23 |
+
|
| 24 |
+
flow = cv2.calcOpticalFlowFarneback(
|
| 25 |
+
prev_small, curr_small,
|
| 26 |
+
flow=None,
|
| 27 |
+
pyr_scale=0.5, levels=3, winsize=15,
|
| 28 |
+
iterations=3, poly_n=5, poly_sigma=1.2, flags=0
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
magnitude, _ = cv2.cartToPolar(flow[..., 0], flow[..., 1])
|
| 32 |
+
motion_variance = np.std(magnitude)
|
| 33 |
+
normalized_score = min(motion_variance / 20.0, 1.0)
|
| 34 |
+
|
| 35 |
+
return float(normalized_score)
|
| 36 |
+
|
| 37 |
+
except Exception as e:
|
| 38 |
+
logger.error(f"Optiocal Flow Crash: {str(e)}")
|
| 39 |
+
return 0.0
|