Candle commited on
Commit ·
2e1670e
1
Parent(s): 284d1e9
detection
Browse filesFiles changed (2)
- detect_loops.py+36-13
- length_penalty_plot.pngAdded
1 unmodified line234567891011121318 unmodified lines3233343536373839404142439 unmodified lines53545556575859606162636465666721 unmodified lines89909192939495969798991001011021031041051061071081 unmodified lineimport numpy as npfrom pathlib import Pathfrom PIL import Imageimport timeimport jsonshots_dir = Path('data/shots')files = sorted(shots_dir.glob('sample-*.webp'))def extract_frames(webp_path):frames = []with Image.open(webp_path) as im:18 unmodified linescos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + eps)return cos_simdef detect_loops(frames, min_len=6, max_len=40, top_k=3):n = len(frames)candidates = []# Preprocess frames: grayscale float32 and downscale to 32x32 (float32)processed_frames = [cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (32, 32), interpolation=cv2.INTER_AREA)for f in frames]# Build 3-channel composite frames: R=prev, G=curr, B=next (looping)9 unmodified linescomposite_frames.append(composite)for i in range(n):for j in range(i+min_len, min(i+max_len, n)):t0 = time.time()# Compare composite frames directlystart_comp = composite_frames[i].astype(np.float32)end_comp = composite_frames[j].astype(np.float32)cos_sim = compute_sim(start_comp, end_comp)t1 = time.time()score = cos_sim # Higher cosine similarity is better# print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")candidates.append((score, i, j, cos_sim))# Sort by score descendingcandidates.sort(reverse=True)return candidates[:top_k]21 unmodified linesprint(f"Extracted {len(frames)} frames from {webp_path}")loops = detect_loops(frames)loop_json = []for score, i, j, cos_sim in loops:loop_json.append({"start": int(i),"end": int(j),"score": float(score),"cos_sim": float(cos_sim)})json_name = f"{webp_path.stem}.loop.json"json_path = output_dir / json_namewith open(json_path, "w") as f:json.dump(loop_json, f, indent=2)print(f"Saved loop candidates: {json_path}")for idx, (score, i, j, cos_sim) in enumerate(loops):print(f"Loop candidate: start={i}, end={j}, score={score:.4f}, COS_SIM={cos_sim:.4f}")if idx != 0:continue # For now, only save the top candidate# Extract loop frames (seamless looping: frames[i:j])1 unmodified line23456789101112131415161718192021222324252627282930313233343518 unmodified lines5455565758596061626364659 unmodified lines757677787980818283848586878821 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311 unmodified lineimport numpy as npfrom pathlib import Pathfrom PIL import Imageimport jsonshots_dir = Path('data/shots')files = sorted(shots_dir.glob('sample-*.webp'))def sigmoid(x):return 1 / (1 + np.exp(-x))def evaluate_length_penalty(len, mag = 0.0045):"""Length penalty function based on sigmoid curves."""x = leny = mag + -mag * sigmoid(0.58 * (x - 1.5)) + 0.25 * mag * sigmoid(2 * (x - 17))return y# Two sigmoids — one dips around x=2, one rises around x=16import matplotlib.pyplot as pltx = np.linspace(0, 40, 400)y = evaluate_length_penalty(x)plt.plot(x, y, 'k', lw=3)plt.axvline(2, color='k', lw=2)plt.axvline(16, color='k', lw=2)plt.text(0, -0.06, '0', ha='center', va='top', fontsize=12)plt.text(2, -0.06, '2', ha='center', va='top', fontsize=12)plt.text(16, -0.06, '16', ha='center', va='top', fontsize=12)# save the plot into length_penalty_plot.pngplt.savefig('length_penalty_plot.png')plt.close()def extract_frames(webp_path):frames = []with Image.open(webp_path) as im:18 unmodified linescos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + eps)return cos_simdef detect_loops(frames, min_len=2, max_len=40, top_k=10):n = len(frames)candidates = []# Preprocess frames: grayscale float32 and downscale to 128x128 (float32)processed_frames = [cv2.resize(cv2.cvtColor(f, cv2.COLOR_BGR2GRAY).astype(np.float32), (128, 128), interpolation=cv2.INTER_AREA)for f in frames]# Build 3-channel composite frames: R=prev, G=curr, B=next (looping)9 unmodified linescomposite_frames.append(composite)for i in range(n):for j in range(i+min_len, min(i+max_len, n)):# Compare composite frames directlystart_comp = composite_frames[i].astype(np.float32)end_comp = composite_frames[j].astype(np.float32)cos_sim = compute_sim(start_comp, end_comp)length_penalty = evaluate_length_penalty(j - i)score = cos_sim - length_penalty # Higher cosine similarity is better# print(f"Loop ({i},{j}): Cosine similarity={cos_sim:.4f} (t={t1-t0:.3f}s)")candidates.append((score, i, j, cos_sim, length_penalty))# Sort by score descendingcandidates.sort(reverse=True)return candidates[:top_k]21 unmodified linesprint(f"Extracted {len(frames)} frames from {webp_path}")loops = detect_loops(frames)loop_json = []for score, i, j, cos_sim, len_penalty in loops:loop_json.append({"start": int(i),"end": int(j),"score": float(score),"cos_sim": float(cos_sim),"length": int(j - i),"length_penalty": float(len_penalty)})json_name = f"{webp_path.stem}.loop.json"json_path = output_dir / json_namewith open(json_path, "w") as f:json.dump(loop_json, f, indent=2)print(f"Saved loop candidates: {json_path}")for idx, (score, i, j, cos_sim, len_penalty) in enumerate(loops):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}")if idx != 0:continue # For now, only save the top candidate# Extract loop frames (seamless looping: frames[i:j])
detect_loops.py+36-13
length_penalty_plot.pngAdded
Large File Pointer Details
- SHA256: d876e403a50b8b5b2e5279af9314403be3adbb2f6daee06e96de11ac568560d3
- Pointer size: 130 Bytes
- Size of remote file: 17.6 kB