Candle commited on
Commit
fbc7128
·
1 Parent(s): aab93cc

loop detect using my own method

Browse files
Files changed (1) hide show
  1. detect_loops.py +10 -24
detect_loops.py CHANGED
@@ -2,7 +2,12 @@ import cv2
2
  import numpy as np
3
  from pathlib import Path
4
  from PIL import Image
5
- from skimage.metrics import structural_similarity as ssim
 
 
 
 
 
6
 
7
  def extract_frames(webp_path):
8
  frames = []
@@ -29,10 +34,8 @@ def compute_sim(f1, f2):
29
  return cos_sim
30
 
31
  def detect_loops(frames, min_len=6, max_len=40, top_k=3):
32
- import time
33
  n = len(frames)
34
  candidates = []
35
- composite_window = 3
36
  # Preprocess frames: grayscale float32 and downscale to 32x32 (float32)
37
  processed_frames = [
38
  cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (32, 32), interpolation=cv2.INTER_AREA)
@@ -58,7 +61,7 @@ def detect_loops(frames, min_len=6, max_len=40, top_k=3):
58
  cos_sim = compute_sim(start_comp, end_comp)
59
  t1 = time.time()
60
  score = cos_sim # Higher cosine similarity is better
61
- print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")
62
  candidates.append((score, i, j, cos_sim))
63
  # Sort by score descending
64
  candidates.sort(reverse=True)
@@ -70,8 +73,6 @@ if __name__ == "__main__":
70
  from glob import glob
71
 
72
  # For batch processing, change the pattern below to 'sample-*.webp' or similar
73
- shots_dir = Path('data/shots')
74
- files = sorted(shots_dir.glob('sample-000-*.webp'))
75
  if not files:
76
  print('No files found.')
77
  sys.exit(1)
@@ -87,24 +88,7 @@ if __name__ == "__main__":
87
  print(f"Processing {webp_path}")
88
  frames = extract_frames(webp_path)
89
  print(f"Extracted {len(frames)} frames from {webp_path}")
90
- # # Show composite image for first frame (3-channel: R=prev, G=curr, B=next)
91
- # processed_frames = [cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY), (64, 64), interpolation=cv2.INTER_AREA) for f in frames]
92
- # n = len(processed_frames)
93
- # if n > 0:
94
- # prev_idx = (0 - 1) % n
95
- # next_idx = (0 + 1) % n
96
- # r = processed_frames[prev_idx]
97
- # g = processed_frames[0]
98
- # b = processed_frames[next_idx]
99
- # composite = np.stack([r, g, b], axis=-1)
100
- # plt.imshow(composite)
101
- # plt.title('Composite: R=prev, G=curr, B=next (grayscale, downscaled)')
102
- # plt.axis('off')
103
- # plt.show()
104
- # Unindent following code to match main block
105
  loops = detect_loops(frames)
106
- # Save all candidates and their scores to JSON
107
- import json
108
  loop_json = []
109
  for score, i, j, cos_sim in loops:
110
  loop_json.append({
@@ -120,12 +104,14 @@ if __name__ == "__main__":
120
  print(f"Saved loop candidates: {json_path}")
121
  for idx, (score, i, j, cos_sim) in enumerate(loops):
122
  print(f"Loop candidate: start={i}, end={j}, score={score:.4f}, COS_SIM={cos_sim:.4f}")
 
 
123
  # Extract loop frames (seamless looping: frames[i:j])
124
  loop_frames = frames[i:j]
125
  # Convert BGR (OpenCV) to RGB for PIL
126
  pil_frames = [Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) for f in loop_frames]
127
  # Save as animated webp
128
- out_name = f"{webp_path.stem}.loop-{idx}.webp"
129
  out_path = output_dir / out_name
130
  pil_frames[0].save(
131
  out_path,
 
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
 
12
  def extract_frames(webp_path):
13
  frames = []
 
34
  return cos_sim
35
 
36
  def detect_loops(frames, min_len=6, max_len=40, top_k=3):
 
37
  n = len(frames)
38
  candidates = []
 
39
  # Preprocess frames: grayscale float32 and downscale to 32x32 (float32)
40
  processed_frames = [
41
  cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (32, 32), interpolation=cv2.INTER_AREA)
 
61
  cos_sim = compute_sim(start_comp, end_comp)
62
  t1 = time.time()
63
  score = cos_sim # Higher cosine similarity is better
64
+ # print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")
65
  candidates.append((score, i, j, cos_sim))
66
  # Sort by score descending
67
  candidates.sort(reverse=True)
 
73
  from glob import glob
74
 
75
  # For batch processing, change the pattern below to 'sample-*.webp' or similar
 
 
76
  if not files:
77
  print('No files found.')
78
  sys.exit(1)
 
88
  print(f"Processing {webp_path}")
89
  frames = extract_frames(webp_path)
90
  print(f"Extracted {len(frames)} frames from {webp_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  loops = detect_loops(frames)
 
 
92
  loop_json = []
93
  for score, i, j, cos_sim in loops:
94
  loop_json.append({
 
104
  print(f"Saved loop candidates: {json_path}")
105
  for idx, (score, i, j, cos_sim) in enumerate(loops):
106
  print(f"Loop candidate: start={i}, end={j}, score={score:.4f}, COS_SIM={cos_sim:.4f}")
107
+ if idx != 0:
108
+ continue # For now, only save the top candidate
109
  # Extract loop frames (seamless looping: frames[i:j])
110
  loop_frames = frames[i:j]
111
  # Convert BGR (OpenCV) to RGB for PIL
112
  pil_frames = [Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) for f in loop_frames]
113
  # Save as animated webp
114
+ out_name = f"{webp_path.stem}.loop.webp"
115
  out_path = output_dir / out_name
116
  pil_frames[0].save(
117
  out_path,