Candle commited on
Commit
41efcac
·
1 Parent(s): 990c24c

don't know

Browse files
Files changed (1) hide show
  1. detect_loops.py +70 -19
detect_loops.py CHANGED
@@ -16,28 +16,48 @@ def extract_frames(webp_path):
16
  pass
17
  return frames
18
 
19
- def compute_flow_magnitude(f1, f2):
20
- prev = cv2.cvtColor(f1, cv2.COLOR_BGR2GRAY)
21
- curr = cv2.cvtColor(f2, cv2.COLOR_BGR2GRAY)
22
- flow = cv2.calcOpticalFlowFarneback(prev, curr, None, 0.5, 3, 15, 3, 5, 1.2, 0)
23
- mag, _ = cv2.cartToPolar(flow[...,0], flow[...,1])
24
- return np.mean(mag)
25
 
26
- def compute_ssim(f1, f2):
27
- # Convert to grayscale for SSIM
28
- g1 = cv2.cvtColor(f1, cv2.COLOR_BGR2GRAY)
29
- g2 = cv2.cvtColor(f2, cv2.COLOR_BGR2GRAY)
30
- return ssim(g1, g2)
31
 
32
  def detect_loops(frames, min_len=6, max_len=40, top_k=3):
 
33
  n = len(frames)
34
  candidates = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  for i in range(n):
36
  for j in range(i+min_len, min(i+max_len, n)):
37
- sim = compute_ssim(frames[i], frames[j])
38
- flow = compute_flow_magnitude(frames[i], frames[j])
39
- score = sim - flow # Higher is better
40
- candidates.append((score, i, j, sim, flow))
 
 
 
 
 
 
 
 
41
  # Sort by score descending
42
  candidates.sort(reverse=True)
43
  return candidates[:top_k]
@@ -60,15 +80,46 @@ if __name__ == "__main__":
60
  output_dir = Path('data/loops')
61
  output_dir.mkdir(parents=True, exist_ok=True)
62
 
 
63
  for webp_path in files:
64
  print(f"Processing {webp_path}")
65
  frames = extract_frames(webp_path)
66
  print(f"Extracted {len(frames)} frames from {webp_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  loops = detect_loops(frames)
68
- for idx, (score, i, j, sim, flow) in enumerate(loops):
69
- print(f"Loop candidate: start={i}, end={j}, score={score:.3f}, SSIM={sim:.3f}, flow={flow:.3f}")
70
- # Extract loop frames
71
- loop_frames = frames[i:j+1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # Convert BGR (OpenCV) to RGB for PIL
73
  pil_frames = [Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) for f in loop_frames]
74
  # Save as animated webp
 
16
  pass
17
  return frames
18
 
 
 
 
 
 
 
19
 
20
+
21
+ def compute_sim(f1, f2):
22
+ # f1 and f2 are already grayscale and downscaled
23
+ mse = np.mean((f1.astype(np.float32) - f2.astype(np.float32)) ** 2)
24
+ return mse
25
 
26
  def detect_loops(frames, min_len=6, max_len=40, top_k=3):
27
+ import time
28
  n = len(frames)
29
  candidates = []
30
+ composite_window = 3
31
+ # Preprocess frames: grayscale float32 and downscale to 32x32 (float32)
32
+ processed_frames = [
33
+ cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (32, 32), interpolation=cv2.INTER_AREA)
34
+ for f in frames
35
+ ]
36
+ # Build 3-channel composite frames: R=prev, G=curr, B=next (looping)
37
+ n = len(processed_frames)
38
+ composite_frames = []
39
+ for idx in range(n):
40
+ prev_idx = (idx - 1) % n
41
+ next_idx = (idx + 1) % n
42
+ r = processed_frames[prev_idx]
43
+ g = processed_frames[idx]
44
+ b = processed_frames[next_idx]
45
+ composite = np.stack([r, g, b], axis=-1)
46
+ composite_frames.append(composite)
47
  for i in range(n):
48
  for j in range(i+min_len, min(i+max_len, n)):
49
+ t0 = time.time()
50
+ # Composite start: average composite frames i, i+1, ..., i+composite_window-1
51
+ start_idxs = range(i, min(i+composite_window, n))
52
+ end_idxs = range(max(j-composite_window+1, i), j+1)
53
+ start_comp = np.mean([composite_frames[idx].astype(np.float32) for idx in start_idxs], axis=0)
54
+ end_comp = np.mean([composite_frames[idx].astype(np.float32) for idx in end_idxs], axis=0)
55
+ # No uint8 conversion; keep float32 for MSE
56
+ sim = compute_sim(start_comp, end_comp)
57
+ t1 = time.time()
58
+ score = -sim # Lower MSE is better, so negate for sorting
59
+ print(f"Loop ({i},{j}): Composite MSE={sim:.1f} (t={t1-t0:.3f}s)")
60
+ candidates.append((score, i, j, sim))
61
  # Sort by score descending
62
  candidates.sort(reverse=True)
63
  return candidates[:top_k]
 
80
  output_dir = Path('data/loops')
81
  output_dir.mkdir(parents=True, exist_ok=True)
82
 
83
+ # import matplotlib.pyplot as plt
84
  for webp_path in files:
85
  print(f"Processing {webp_path}")
86
  frames = extract_frames(webp_path)
87
  print(f"Extracted {len(frames)} frames from {webp_path}")
88
+ # # Show composite image for first frame (3-channel: R=prev, G=curr, B=next)
89
+ # processed_frames = [cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY), (64, 64), interpolation=cv2.INTER_AREA) for f in frames]
90
+ # n = len(processed_frames)
91
+ # if n > 0:
92
+ # prev_idx = (0 - 1) % n
93
+ # next_idx = (0 + 1) % n
94
+ # r = processed_frames[prev_idx]
95
+ # g = processed_frames[0]
96
+ # b = processed_frames[next_idx]
97
+ # composite = np.stack([r, g, b], axis=-1)
98
+ # plt.imshow(composite)
99
+ # plt.title('Composite: R=prev, G=curr, B=next (grayscale, downscaled)')
100
+ # plt.axis('off')
101
+ # plt.show()
102
+ # Unindent following code to match main block
103
  loops = detect_loops(frames)
104
+ # Save all candidates and their scores to JSON
105
+ import json
106
+ loop_json = []
107
+ for score, i, j, sim in loops:
108
+ loop_json.append({
109
+ "start": int(i),
110
+ "end": int(j),
111
+ "score": float(score),
112
+ "sim": float(sim)
113
+ })
114
+ json_name = f"{webp_path.stem}.loop.json"
115
+ json_path = output_dir / json_name
116
+ with open(json_path, "w") as f:
117
+ json.dump(loop_json, f, indent=2)
118
+ print(f"Saved loop candidates: {json_path}")
119
+ for idx, (score, i, j, sim) in enumerate(loops):
120
+ print(f"Loop candidate: start={i}, end={j}, score={score:.3f}, SIM={sim:.3f}")
121
+ # Extract loop frames (seamless looping: frames[i:j])
122
+ loop_frames = frames[i:j]
123
  # Convert BGR (OpenCV) to RGB for PIL
124
  pil_frames = [Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) for f in loop_frames]
125
  # Save as animated webp