Candle commited on
Commit
2227933
·
1 Parent(s): 54b61a4

motion correction... I really need a better one. I need a ML model

Browse files
Files changed (1) hide show
  1. detect_loops.py +30 -16
detect_loops.py CHANGED
@@ -13,7 +13,7 @@ def sigmoid(x):
13
  def evaluate_length_penalty(len, mag = 0.0045):
14
  """Length penalty function based on sigmoid curves."""
15
  x = len
16
- y = mag + -mag * sigmoid(0.58 * (x - 1.5)) + 0.25 * mag * sigmoid(2 * (x - 17))
17
  return y
18
 
19
  # Two sigmoids — one dips around x=2, one rises around x=16
@@ -21,7 +21,7 @@ import matplotlib.pyplot as plt
21
  x = np.linspace(0, 40, 400)
22
  y = evaluate_length_penalty(x)
23
  plt.plot(x, y, 'k', lw=3)
24
- plt.axvline(2, color='k', lw=2)
25
  plt.axvline(16, color='k', lw=2)
26
  plt.text(0, -0.06, '0', ha='center', va='top', fontsize=12)
27
  plt.text(2, -0.06, '2', ha='center', va='top', fontsize=12)
@@ -54,7 +54,7 @@ def compute_sim(f1, f2):
54
  cos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + eps)
55
  return cos_sim
56
 
57
- def detect_loops(frames, min_len=2, max_len=40, top_k=10):
58
  n = len(frames)
59
  candidates = []
60
  # Preprocess frames: grayscale float32 and downscale to 128x128 (float32)
@@ -65,6 +65,7 @@ def detect_loops(frames, min_len=2, max_len=40, top_k=10):
65
  # Build 3-channel composite frames: R=prev, G=curr, B=next (looping)
66
  n = len(processed_frames)
67
  composite_frames = []
 
68
  for idx in range(n):
69
  prev_idx = (idx - 1) % n
70
  next_idx = (idx + 1) % n
@@ -73,6 +74,21 @@ def detect_loops(frames, min_len=2, max_len=40, top_k=10):
73
  b = processed_frames[next_idx]
74
  composite = np.stack([r, g, b], axis=-1)
75
  composite_frames.append(composite)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  for i in range(n):
77
  for j in range(i+min_len, min(i+max_len, n)):
78
  # Compare composite frames directly
@@ -80,26 +96,24 @@ def detect_loops(frames, min_len=2, max_len=40, top_k=10):
80
  end_comp = composite_frames[j].astype(np.float32)
81
  cos_sim = compute_sim(start_comp, end_comp)
82
  length_penalty = evaluate_length_penalty(j - i)
83
- score = cos_sim - length_penalty # Higher cosine similarity is better
 
 
 
84
  # print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")
85
- candidates.append((score, i, j, cos_sim, length_penalty))
86
  # Sort by score descending
87
  candidates.sort(reverse=True)
88
  return candidates[:top_k]
89
 
90
  if __name__ == "__main__":
91
- # Example usage: python detect_loops.py data/shots/sample-000-0.webp
92
- import sys
93
- from glob import glob
94
 
95
  # For batch processing, change the pattern below to 'sample-*.webp' or similar
96
  if not files:
97
  print('No files found.')
 
98
  sys.exit(1)
99
 
100
- import os
101
- from PIL import Image
102
-
103
  output_dir = Path('data/loops')
104
  output_dir.mkdir(parents=True, exist_ok=True)
105
 
@@ -110,22 +124,23 @@ if __name__ == "__main__":
110
  print(f"Extracted {len(frames)} frames from {webp_path}")
111
  loops = detect_loops(frames)
112
  loop_json = []
113
- for score, i, j, cos_sim, len_penalty in loops:
114
  loop_json.append({
115
  "start": int(i),
116
  "end": int(j),
117
  "score": float(score),
118
  "cos_sim": float(cos_sim),
119
  "length": int(j - i),
120
- "length_penalty": float(len_penalty)
 
121
  })
122
  json_name = f"{webp_path.stem}.loop.json"
123
  json_path = output_dir / json_name
124
  with open(json_path, "w") as f:
125
  json.dump(loop_json, f, indent=2)
126
  print(f"Saved loop candidates: {json_path}")
127
- for idx, (score, i, j, cos_sim, len_penalty) in enumerate(loops):
128
- print(f"Loop candidate: start={i}, end={j}, score={score:.6f}, COS_SIM={cos_sim:.6f}, LEN={int(j - i)}, LEN_PENALTY={len_penalty:.6f}")
129
  if idx != 0:
130
  continue # For now, only save the top candidate
131
  # Extract loop frames (seamless looping: frames[i:j])
@@ -143,4 +158,3 @@ if __name__ == "__main__":
143
  loop=0,
144
  lossless=True
145
  )
146
- print(f"Saved loop: {out_path}")
 
13
  def evaluate_length_penalty(len, mag = 0.0045):
14
  """Length penalty function based on sigmoid curves."""
15
  x = len
16
+ y = mag + -mag * sigmoid(0.58 * (x - 1.65)) + 0.25 * mag * sigmoid(2 * (x - 17))
17
  return y
18
 
19
  # Two sigmoids — one dips around x=2, one rises around x=16
 
21
  x = np.linspace(0, 40, 400)
22
  y = evaluate_length_penalty(x)
23
  plt.plot(x, y, 'k', lw=3)
24
+ plt.axvline(4, color='k', lw=2)
25
  plt.axvline(16, color='k', lw=2)
26
  plt.text(0, -0.06, '0', ha='center', va='top', fontsize=12)
27
  plt.text(2, -0.06, '2', ha='center', va='top', fontsize=12)
 
54
  cos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + eps)
55
  return cos_sim
56
 
57
+ def detect_loops(frames, min_len=4, max_len=40, top_k=10):
58
  n = len(frames)
59
  candidates = []
60
  # Preprocess frames: grayscale float32 and downscale to 128x128 (float32)
 
65
  # Build 3-channel composite frames: R=prev, G=curr, B=next (looping)
66
  n = len(processed_frames)
67
  composite_frames = []
68
+ motion_energies = []
69
  for idx in range(n):
70
  prev_idx = (idx - 1) % n
71
  next_idx = (idx + 1) % n
 
74
  b = processed_frames[next_idx]
75
  composite = np.stack([r, g, b], axis=-1)
76
  composite_frames.append(composite)
77
+ if idx == n - 1:
78
+ motion_energies.append(0.0)
79
+ else:
80
+ # waving hand 0.97
81
+ # body shake 1.78
82
+ # running 15.0
83
+ # breathing 0.56
84
+ # talking 0.39
85
+ motion_energy = np.mean(np.abs(processed_frames[next_idx] - processed_frames[idx]))
86
+ motion_energies.append(motion_energy)
87
+ max_motion_energy = 20.0
88
+ normalized_motion_energies = []
89
+ for me in motion_energies:
90
+ nme = min(me / max_motion_energy, 1.0)
91
+ normalized_motion_energies.append(nme)
92
  for i in range(n):
93
  for j in range(i+min_len, min(i+max_len, n)):
94
  # Compare composite frames directly
 
96
  end_comp = composite_frames[j].astype(np.float32)
97
  cos_sim = compute_sim(start_comp, end_comp)
98
  length_penalty = evaluate_length_penalty(j - i)
99
+ motion_energy = motion_energies[i]
100
+ nme = normalized_motion_energies[i]
101
+ similarity_correction = (1.0 - cos_sim) * nme * 0.5
102
+ score = cos_sim + similarity_correction - length_penalty # Higher cosine similarity is better
103
  # print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")
104
+ candidates.append((score, i, j, cos_sim, length_penalty, motion_energy))
105
  # Sort by score descending
106
  candidates.sort(reverse=True)
107
  return candidates[:top_k]
108
 
109
  if __name__ == "__main__":
 
 
 
110
 
111
  # For batch processing, change the pattern below to 'sample-*.webp' or similar
112
  if not files:
113
  print('No files found.')
114
+ import sys
115
  sys.exit(1)
116
 
 
 
 
117
  output_dir = Path('data/loops')
118
  output_dir.mkdir(parents=True, exist_ok=True)
119
 
 
124
  print(f"Extracted {len(frames)} frames from {webp_path}")
125
  loops = detect_loops(frames)
126
  loop_json = []
127
+ for score, i, j, cos_sim, len_penalty, motion_energy in loops:
128
  loop_json.append({
129
  "start": int(i),
130
  "end": int(j),
131
  "score": float(score),
132
  "cos_sim": float(cos_sim),
133
  "length": int(j - i),
134
+ "length_penalty": float(len_penalty),
135
+ "motion_energy": float(len_penalty)
136
  })
137
  json_name = f"{webp_path.stem}.loop.json"
138
  json_path = output_dir / json_name
139
  with open(json_path, "w") as f:
140
  json.dump(loop_json, f, indent=2)
141
  print(f"Saved loop candidates: {json_path}")
142
+ for idx, (score, i, j, cos_sim, len_penalty, motion_energy) in enumerate(loops):
143
+ print(f"Loop candidate: start={i}, end={j}, score={score:.6f}, COS_SIM={cos_sim:.6f}, LEN={int(j - i)}, LEN_PENALTY={len_penalty:.6f}, MOTION_ENERGY={motion_energy:.6f}")
144
  if idx != 0:
145
  continue # For now, only save the top candidate
146
  # Extract loop frames (seamless looping: frames[i:j])
 
158
  loop=0,
159
  lossless=True
160
  )