Candle commited on
Commit
2e1670e
·
1 Parent(s): 284d1e9

detection

Browse files
Files changed (2) hide show
  1. detect_loops.py +36 -13
  2. length_penalty_plot.png +3 -0
detect_loops.py CHANGED
@@ -2,12 +2,34 @@ import cv2
2
  import numpy as np
3
  from pathlib import Path
4
  from PIL import Image
5
- import time
6
  import json
7
 
8
  shots_dir = Path('data/shots')
9
  files = sorted(shots_dir.glob('sample-*.webp'))
10
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  def extract_frames(webp_path):
12
  frames = []
13
  with Image.open(webp_path) as im:
@@ -32,12 +54,12 @@ def compute_sim(f1, f2):
32
  cos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + eps)
33
  return cos_sim
34
 
35
- def detect_loops(frames, min_len=6, max_len=40, top_k=3):
36
  n = len(frames)
37
  candidates = []
38
- # Preprocess frames: grayscale float32 and downscale to 32x32 (float32)
39
  processed_frames = [
40
- cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (32, 32), interpolation=cv2.INTER_AREA)
41
  for f in frames
42
  ]
43
  # Build 3-channel composite frames: R=prev, G=curr, B=next (looping)
@@ -53,15 +75,14 @@ def detect_loops(frames, min_len=6, max_len=40, top_k=3):
53
  composite_frames.append(composite)
54
  for i in range(n):
55
  for j in range(i+min_len, min(i+max_len, n)):
56
- t0 = time.time()
57
  # Compare composite frames directly
58
  start_comp = composite_frames[i].astype(np.float32)
59
  end_comp = composite_frames[j].astype(np.float32)
60
  cos_sim = compute_sim(start_comp, end_comp)
61
- t1 = time.time()
62
- score = cos_sim # Higher cosine similarity is better
63
  # print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")
64
- candidates.append((score, i, j, cos_sim))
65
  # Sort by score descending
66
  candidates.sort(reverse=True)
67
  return candidates[:top_k]
@@ -89,20 +110,22 @@ if __name__ == "__main__":
89
  print(f"Extracted {len(frames)} frames from {webp_path}")
90
  loops = detect_loops(frames)
91
  loop_json = []
92
- for score, i, j, cos_sim in loops:
93
  loop_json.append({
94
  "start": int(i),
95
  "end": int(j),
96
  "score": float(score),
97
- "cos_sim": float(cos_sim)
 
 
98
  })
99
  json_name = f"{webp_path.stem}.loop.json"
100
  json_path = output_dir / json_name
101
  with open(json_path, "w") as f:
102
  json.dump(loop_json, f, indent=2)
103
  print(f"Saved loop candidates: {json_path}")
104
- for idx, (score, i, j, cos_sim) in enumerate(loops):
105
- print(f"Loop candidate: start={i}, end={j}, score={score:.4f}, COS_SIM={cos_sim:.4f}")
106
  if idx != 0:
107
  continue # For now, only save the top candidate
108
  # Extract loop frames (seamless looping: frames[i:j])
 
2
  import numpy as np
3
  from pathlib import Path
4
  from PIL import Image
 
5
  import json
6
 
7
  shots_dir = Path('data/shots')
8
  files = sorted(shots_dir.glob('sample-*.webp'))
9
+
10
+ def sigmoid(x):
11
+ return 1 / (1 + np.exp(-x))
12
+
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
20
+ 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)
28
+ plt.text(16, -0.06, '16', ha='center', va='top', fontsize=12)
29
+ # save the plot into length_penalty_plot.png
30
+ plt.savefig('length_penalty_plot.png')
31
+ plt.close()
32
+
33
  def extract_frames(webp_path):
34
  frames = []
35
  with Image.open(webp_path) as im:
 
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)
61
  processed_frames = [
62
+ cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (128, 128), interpolation=cv2.INTER_AREA)
63
  for f in frames
64
  ]
65
  # Build 3-channel composite frames: R=prev, G=curr, B=next (looping)
 
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
79
  start_comp = composite_frames[i].astype(np.float32)
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]
 
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])
length_penalty_plot.png ADDED

Git LFS Details

  • SHA256: d876e403a50b8b5b2e5279af9314403be3adbb2f6daee06e96de11ac568560d3
  • Pointer size: 130 Bytes
  • Size of remote file: 17.6 kB