Spaces:
Runtime error
Runtime error
Update animation_logic.py
Browse files- animation_logic.py +48 -0
animation_logic.py
CHANGED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import numexpr
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
def parse_keyframe_string(string, max_frames):
|
| 7 |
+
"""Parses '0:(val), 10:(val)' strings into a per-frame float array."""
|
| 8 |
+
res = np.ones(max_frames)
|
| 9 |
+
parts = string.split(",")
|
| 10 |
+
keyframes = {}
|
| 11 |
+
for part in parts:
|
| 12 |
+
try:
|
| 13 |
+
k, v = part.split(":")
|
| 14 |
+
keyframes[int(k.strip())] = v.strip("() ")
|
| 15 |
+
except: continue
|
| 16 |
+
|
| 17 |
+
sorted_keys = sorted(keyframes.keys())
|
| 18 |
+
for i in range(len(sorted_keys)):
|
| 19 |
+
start_f = sorted_keys[i]
|
| 20 |
+
end_f = sorted_keys[i+1] if i+1 < len(sorted_keys) else max_frames
|
| 21 |
+
val_str = keyframes[start_f]
|
| 22 |
+
|
| 23 |
+
for f in range(start_f, end_f):
|
| 24 |
+
if val_str.replace('.','',1).isdigit():
|
| 25 |
+
res[f] = float(val_str)
|
| 26 |
+
else:
|
| 27 |
+
t = f
|
| 28 |
+
try:
|
| 29 |
+
res[f] = numexpr.evaluate(val_str, local_dict={'t': t, 'sin': np.sin, 'cos': np.cos, 'pi': np.pi}).item()
|
| 30 |
+
except:
|
| 31 |
+
res[f] = res[f-1] if f > 0 else 0.0
|
| 32 |
+
return res
|
| 33 |
+
|
| 34 |
+
def anim_frame_warp(img, angle, zoom, translation_x, translation_y):
|
| 35 |
+
"""Performs 2D affine transformation on a PIL Image."""
|
| 36 |
+
width, height = img.size
|
| 37 |
+
center = (width // 2, height // 2)
|
| 38 |
+
matrix = cv2.getRotationMatrix2D(center, angle, zoom)
|
| 39 |
+
matrix[0, 2] += translation_x
|
| 40 |
+
matrix[1, 2] += translation_y
|
| 41 |
+
return Image.fromarray(cv2.warpAffine(np.array(img), matrix, (width, height), borderMode=cv2.BORDER_REPLICATE))
|
| 42 |
+
|
| 43 |
+
def lerp_frames(frame1, frame2, alpha):
|
| 44 |
+
"""Linearly interpolates between two images for Cadence."""
|
| 45 |
+
arr1 = np.array(frame1).astype(np.float32)
|
| 46 |
+
arr2 = np.array(frame2).astype(np.float32)
|
| 47 |
+
blended = arr1 * (1 - alpha) + arr2 * alpha
|
| 48 |
+
return Image.fromarray(blended.astype(np.uint8))
|