Deforum_Soonr / dev /animation_logic1.py
AlekseyCalvin's picture
Rename animation_logic1.py to dev/animation_logic1.py
a5bde82 verified
import numpy as np
import cv2
import numexpr
from PIL import Image
def parse_keyframe_string(string, max_frames):
"""Parses '0:(val), 10:(val)' strings into a per-frame float array."""
res = np.ones(max_frames)
parts = string.split(",")
keyframes = {}
for part in parts:
try:
k, v = part.split(":")
keyframes[int(k.strip())] = v.strip("() ")
except: continue
sorted_keys = sorted(keyframes.keys())
for i in range(len(sorted_keys)):
start_f = sorted_keys[i]
end_f = sorted_keys[i+1] if i+1 < len(sorted_keys) else max_frames
val_str = keyframes[start_f]
for f in range(start_f, end_f):
if val_str.replace('.','',1).isdigit():
res[f] = float(val_str)
else:
t = f
try:
res[f] = numexpr.evaluate(val_str, local_dict={'t': t, 'sin': np.sin, 'cos': np.cos, 'pi': np.pi}).item()
except:
res[f] = res[f-1] if f > 0 else 0.0
return res
def anim_frame_warp(img, angle, zoom, translation_x, translation_y):
"""Performs 2D affine transformation on a PIL Image."""
width, height = img.size
center = (width // 2, height // 2)
matrix = cv2.getRotationMatrix2D(center, angle, zoom)
matrix[0, 2] += translation_x
matrix[1, 2] += translation_y
return Image.fromarray(cv2.warpAffine(np.array(img), matrix, (width, height), borderMode=cv2.BORDER_REPLICATE))
def lerp_frames(frame1, frame2, alpha):
"""Linearly interpolates between two images for Cadence."""
arr1 = np.array(frame1).astype(np.float32)
arr2 = np.array(frame2).astype(np.float32)
blended = arr1 * (1 - alpha) + arr2 * alpha
return Image.fromarray(blended.astype(np.uint8))