File size: 6,313 Bytes
990c24c
 
 
 
fbc7128
 
 
 
2e1670e
 
 
 
 
 
 
2227933
2e1670e
 
 
 
 
 
 
2227933
2e1670e
 
 
 
 
 
 
 
990c24c
 
 
 
 
 
 
 
 
 
 
 
41efcac
aab93cc
 
 
 
 
 
 
 
 
 
990c24c
2227933
990c24c
 
2e1670e
41efcac
2e1670e
41efcac
 
 
 
 
2227933
41efcac
 
 
 
 
 
 
 
2227933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
990c24c
 
57d6cb5
 
 
aab93cc
2e1670e
2227933
 
 
 
fbc7128
2227933
990c24c
 
 
 
 
 
 
 
 
2227933
990c24c
 
 
 
 
41efcac
990c24c
 
 
 
 
41efcac
2227933
41efcac
 
 
 
2e1670e
 
2227933
 
41efcac
 
 
 
 
 
2227933
 
fbc7128
 
41efcac
 
990c24c
 
 
fbc7128
990c24c
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import cv2
import numpy as np
from pathlib import Path
from PIL import Image
import json

shots_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 = len
    y = mag + -mag * sigmoid(0.58 * (x - 1.65)) + 0.25 * mag * sigmoid(2 * (x - 17))    
    return y

# Two sigmoids — one dips around x=2, one rises around x=16
import matplotlib.pyplot as plt
x = np.linspace(0, 40, 400)
y = evaluate_length_penalty(x)
plt.plot(x, y, 'k', lw=3)
plt.axvline(4, 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.png
plt.savefig('length_penalty_plot.png')
plt.close()

def extract_frames(webp_path):
    frames = []
    with Image.open(webp_path) as im:
        try:
            while True:
                frame = im.convert('RGB')
                frames.append(np.array(frame)[:, :, ::-1])  # RGB to BGR
                im.seek(im.tell() + 1)
        except EOFError:
            pass
    return frames

def compute_sim(f1, f2):
    assert f1.shape == f2.shape, f"Shape mismatch: {f1.shape} vs {f2.shape}"
    assert f1.shape[2] == 3, f"Expected 3 channels, got {f1.shape[2]}"
    assert f1.dtype == np.float32, f"Expected float32, got {f1.dtype}"
    assert f2.dtype == np.float32, f"Expected float32, got {f2.dtype}"
    # Flatten to 1D vectors
    v1 = f1.flatten()
    v2 = f2.flatten()
    eps = 1e-8
    cos_sim = np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2) + eps)
    return cos_sim

def detect_loops(frames, min_len=4, 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)
    n = len(processed_frames)
    composite_frames = []
    motion_energies = []
    for idx in range(n):
        prev_idx = (idx - 1) % n
        next_idx = (idx + 1) % n
        r = processed_frames[prev_idx]
        g = processed_frames[idx]
        b = processed_frames[next_idx]
        composite = np.stack([r, g, b], axis=-1)
        composite_frames.append(composite)
        if idx == n - 1:
            motion_energies.append(0.0)
        else:
            # waving hand 0.97
            # body shake 1.78
            # running 15.0
            # breathing 0.56
            # talking 0.39
            motion_energy = np.mean(np.abs(processed_frames[next_idx] - processed_frames[idx]))
            motion_energies.append(motion_energy)
    max_motion_energy = 20.0
    normalized_motion_energies = []
    for me in motion_energies:
        nme = min(me / max_motion_energy, 1.0)
        normalized_motion_energies.append(nme)
    for i in range(n):
        for j in range(i+min_len, min(i+max_len, n)):
            # Compare composite frames directly
            start_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)
            motion_energy = motion_energies[i]
            nme = normalized_motion_energies[i]
            similarity_correction = (1.0 - cos_sim) * nme * 0.5
            score = cos_sim + similarity_correction - 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, motion_energy))
    # Sort by score descending
    candidates.sort(reverse=True)
    return candidates[:top_k]

if __name__ == "__main__":

    # For batch processing, change the pattern below to 'sample-*.webp' or similar
    if not files:
        print('No files found.')
        import sys
        sys.exit(1)

    output_dir = Path('data/loops')
    output_dir.mkdir(parents=True, exist_ok=True)

    # import matplotlib.pyplot as plt
    for webp_path in files:
        print(f"Processing {webp_path}")
        frames = extract_frames(webp_path)
        print(f"Extracted {len(frames)} frames from {webp_path}")
        loops = detect_loops(frames)
        loop_json = []
        for score, i, j, cos_sim, len_penalty, motion_energy 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),
                "motion_energy": float(len_penalty)
            })
        json_name = f"{webp_path.stem}.loop.json"
        json_path = output_dir / json_name
        with 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, motion_energy) 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}, MOTION_ENERGY={motion_energy:.6f}")
            if idx != 0:
                continue  # For now, only save the top candidate
            # Extract loop frames (seamless looping: frames[i:j])
            loop_frames = frames[i:j]
            # Convert BGR (OpenCV) to RGB for PIL
            pil_frames = [Image.fromarray(cv2.cvtColor(f, cv2.COLOR_BGR2RGB)) for f in loop_frames]
            # Save as animated webp
            out_name = f"{webp_path.stem}.loop.webp"
            out_path = output_dir / out_name
            pil_frames[0].save(
                out_path,
                save_all=True,
                append_images=pil_frames[1:],
                duration=40,  # default duration, can be improved by extracting from original
                loop=0,
                lossless=True
            )