Spaces:
Running
on
Zero
Running
on
Zero
update(*): debug update.
Browse files- app.py +1 -0
- util/env_resolver.py +16 -0
- util/optical_flow.py +0 -140
app.py
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
|
|
| 1 |
import spaces
|
| 2 |
import torch
|
| 3 |
import numpy as np
|
|
|
|
| 1 |
+
import util.env_resolver
|
| 2 |
import spaces
|
| 3 |
import torch
|
| 4 |
import numpy as np
|
util/env_resolver.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
def install_flash_attn():
|
| 5 |
+
try:
|
| 6 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "/home/user/app/wheels/flash_attn-2.8.2+cu129torch2.8-cp310-cp310-linux_x86_64.whl", "--no-build-isolation"])
|
| 7 |
+
print(f"Successfully installed flash_attn")
|
| 8 |
+
except subprocess.CalledProcessError as e:
|
| 9 |
+
print(f"Error installing flash_attn: {e}. This demo won't work properly.")
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import flash_attn
|
| 13 |
+
print(f"`flash_attn` has been installed.")
|
| 14 |
+
except ImportError:
|
| 15 |
+
print(f"`flash_attn` is NOT installed. Trying to install from local wheel...")
|
| 16 |
+
install_flash_attn()
|
util/optical_flow.py
DELETED
|
@@ -1,140 +0,0 @@
|
|
| 1 |
-
import cv2
|
| 2 |
-
import numpy as np
|
| 3 |
-
import torch
|
| 4 |
-
import torch.nn.functional as F
|
| 5 |
-
from torchvision.models.optical_flow import Raft_Large_Weights, raft_large
|
| 6 |
-
from typing import List, Tuple, Dict
|
| 7 |
-
import argparse
|
| 8 |
-
from pathlib import Path
|
| 9 |
-
from sklearn.cluster import KMeans
|
| 10 |
-
from tqdm import tqdm
|
| 11 |
-
import os
|
| 12 |
-
|
| 13 |
-
os.environ['OPENBLAS_NUM_THREADS'] = '64'
|
| 14 |
-
|
| 15 |
-
class OpticalFlowAnalyzer:
|
| 16 |
-
def __init__(self, device: str = 'cuda' if torch.cuda.is_available() else 'cpu'):
|
| 17 |
-
self.device = device
|
| 18 |
-
self.model = raft_large(weights=Raft_Large_Weights.DEFAULT, progress=False).to(device)
|
| 19 |
-
self.model.eval()
|
| 20 |
-
|
| 21 |
-
def preprocess_frame(self, frame: np.ndarray) -> torch.Tensor:
|
| 22 |
-
"""Preprocess a frame for RAFT model."""
|
| 23 |
-
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 24 |
-
frame = torch.from_numpy(frame).permute(2, 0, 1).float()
|
| 25 |
-
frame = frame.unsqueeze(0) / 255.0
|
| 26 |
-
return frame.to(self.device)
|
| 27 |
-
|
| 28 |
-
def compute_optical_flow(self, frame1: np.ndarray, frame2: np.ndarray) -> np.ndarray:
|
| 29 |
-
"""Compute optical flow between two consecutive frames."""
|
| 30 |
-
with torch.no_grad():
|
| 31 |
-
frame1_tensor = self.preprocess_frame(frame1)
|
| 32 |
-
frame2_tensor = self.preprocess_frame(frame2)
|
| 33 |
-
|
| 34 |
-
flow = self.model(frame1_tensor, frame2_tensor)[-1]
|
| 35 |
-
flow = flow[0].permute(1, 2, 0).cpu().numpy()
|
| 36 |
-
|
| 37 |
-
return flow
|
| 38 |
-
|
| 39 |
-
def analyze_motion_regions(self, flow: np.ndarray, num_clusters: int = 3) -> Tuple[np.ndarray, Dict]:
|
| 40 |
-
"""Cluster motion regions based on optical flow magnitude and direction."""
|
| 41 |
-
h, w = flow.shape[:2]
|
| 42 |
-
magnitude = np.sqrt(flow[..., 0]**2 + flow[..., 1]**2)
|
| 43 |
-
direction = np.arctan2(flow[..., 1], flow[..., 0])
|
| 44 |
-
|
| 45 |
-
# Create feature matrix for clustering
|
| 46 |
-
features = np.zeros((h * w, 3))
|
| 47 |
-
features[:, 0] = magnitude.ravel()
|
| 48 |
-
features[:, 1] = np.cos(direction).ravel()
|
| 49 |
-
features[:, 2] = np.sin(direction).ravel()
|
| 50 |
-
|
| 51 |
-
# Normalize features
|
| 52 |
-
features = (features - features.mean(axis=0)) / features.std(axis=0)
|
| 53 |
-
|
| 54 |
-
# Perform clustering
|
| 55 |
-
kmeans = KMeans(n_clusters=num_clusters, random_state=42,)
|
| 56 |
-
labels = kmeans.fit_predict(features)
|
| 57 |
-
labels = labels.reshape(h, w)
|
| 58 |
-
|
| 59 |
-
# Analyze clusters
|
| 60 |
-
cluster_stats = {}
|
| 61 |
-
for i in range(num_clusters):
|
| 62 |
-
cluster_mask = (labels == i)
|
| 63 |
-
cluster_magnitude = magnitude[cluster_mask]
|
| 64 |
-
cluster_stats[i] = {
|
| 65 |
-
'mean_magnitude': np.mean(cluster_magnitude),
|
| 66 |
-
'std_magnitude': np.std(cluster_magnitude),
|
| 67 |
-
'pixel_count': np.sum(cluster_mask),
|
| 68 |
-
'is_static': np.mean(cluster_magnitude) < 0.1 # Threshold for static regions
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
return labels, cluster_stats
|
| 72 |
-
|
| 73 |
-
def process_video(self, video_path: str, output_path: str = None) -> List[Tuple[np.ndarray, Dict]]:
|
| 74 |
-
"""Process a video and return motion analysis results for each frame pair."""
|
| 75 |
-
cap = cv2.VideoCapture(video_path)
|
| 76 |
-
if not cap.isOpened():
|
| 77 |
-
raise ValueError(f"Could not open video: {video_path}")
|
| 78 |
-
|
| 79 |
-
results = []
|
| 80 |
-
ret, prev_frame = cap.read()
|
| 81 |
-
if not ret:
|
| 82 |
-
raise ValueError("Could not read first frame")
|
| 83 |
-
|
| 84 |
-
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 85 |
-
pbar = tqdm(total=total_frames-1, desc="Processing video")
|
| 86 |
-
|
| 87 |
-
while True:
|
| 88 |
-
ret, curr_frame = cap.read()
|
| 89 |
-
if not ret:
|
| 90 |
-
break
|
| 91 |
-
|
| 92 |
-
flow = self.compute_optical_flow(prev_frame, curr_frame)
|
| 93 |
-
labels, stats = self.analyze_motion_regions(flow)
|
| 94 |
-
|
| 95 |
-
if output_path:
|
| 96 |
-
# Visualize results
|
| 97 |
-
vis_frame = curr_frame.copy()
|
| 98 |
-
for i, stat in stats.items():
|
| 99 |
-
if not stat['is_static']:
|
| 100 |
-
mask = (labels == i).astype(np.uint8) * 255
|
| 101 |
-
print("mask:",mask.shape)
|
| 102 |
-
print("vis_frame:",vis_frame.shape)
|
| 103 |
-
mask = np.expand_dims(mask, axis=-1).repeat(3, axis=-1)
|
| 104 |
-
print("mask:",mask.shape)
|
| 105 |
-
|
| 106 |
-
vis_frame[mask > 0] = cv2.addWeighted(vis_frame[mask > 0], 0.7, 255, 0.3, 0)
|
| 107 |
-
|
| 108 |
-
cv2.imwrite(f"{output_path}/frame_{len(results):04d}.jpg", vis_frame)
|
| 109 |
-
|
| 110 |
-
results.append((labels, stats))
|
| 111 |
-
prev_frame = curr_frame
|
| 112 |
-
pbar.update(1)
|
| 113 |
-
|
| 114 |
-
cap.release()
|
| 115 |
-
pbar.close()
|
| 116 |
-
return results
|
| 117 |
-
|
| 118 |
-
def main():
|
| 119 |
-
parser = argparse.ArgumentParser(description='Analyze motion regions in a video using RAFT optical flow')
|
| 120 |
-
parser.add_argument('--video', type=str, required=True, help='Path to input video')
|
| 121 |
-
parser.add_argument('--output', type=str, help='Path to output directory for visualization')
|
| 122 |
-
parser.add_argument('--clusters', type=int, default=3, help='Number of motion clusters')
|
| 123 |
-
args = parser.parse_args()
|
| 124 |
-
|
| 125 |
-
analyzer = OpticalFlowAnalyzer()
|
| 126 |
-
results = analyzer.process_video(args.video, args.output)
|
| 127 |
-
|
| 128 |
-
# Print summary statistics
|
| 129 |
-
print("\nMotion Analysis Summary:")
|
| 130 |
-
for i, (_, stats) in enumerate(results):
|
| 131 |
-
print(f"\nFrame {i+1}:")
|
| 132 |
-
for cluster_id, stat in stats.items():
|
| 133 |
-
motion_type = "Static" if stat['is_static'] else "Moving"
|
| 134 |
-
print(f" Cluster {cluster_id} ({motion_type}):")
|
| 135 |
-
print(f" Mean magnitude: {stat['mean_magnitude']:.4f}")
|
| 136 |
-
print(f" Pixel count: {stat['pixel_count']}")
|
| 137 |
-
|
| 138 |
-
if __name__ == "__main__":
|
| 139 |
-
main()
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|