AlekseyCalvin commited on
Commit
e629302
·
verified ·
1 Parent(s): 49e32ac

Create animation_logic.py

Browse files
Files changed (1) hide show
  1. animation_logic.py +56 -0
animation_logic.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ res = np.ones(max_frames)
8
+ parts = string.split(",")
9
+ keyframes = {}
10
+ for part in parts:
11
+ try:
12
+ k, v = part.split(":")
13
+ keyframes[int(k.strip())] = v.strip("() ")
14
+ except: continue
15
+
16
+ sorted_keys = sorted(keyframes.keys())
17
+ for i in range(len(sorted_keys)):
18
+ start_f = sorted_keys[i]
19
+ end_f = sorted_keys[i+1] if i+1 < len(sorted_keys) else max_frames
20
+ val_str = keyframes[start_f]
21
+
22
+ for f in range(start_f, end_f):
23
+ if val_str.replace('.','',1).isdigit():
24
+ res[f] = float(val_str)
25
+ else:
26
+ try:
27
+ res[f] = numexpr.evaluate(val_str, local_dict={'t': f, 'sin': np.sin, 'cos': np.cos, 'pi': np.pi}).item()
28
+ except:
29
+ res[f] = res[f-1] if f > 0 else 0.0
30
+ return res
31
+
32
+ def maintain_colors(prev_img, target_img):
33
+ """Matches the color histogram of the new frame to the first frame/previous frame."""
34
+ prev_img_cv = cv2.cvtColor(np.array(prev_img), cv2.COLOR_RGB2LAB)
35
+ target_img_cv = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2LAB)
36
+
37
+ avg_l, avg_a, avg_b = np.mean(prev_img_cv[:,:,0]), np.mean(prev_img_cv[:,:,1]), np.mean(prev_img_cv[:,:,2])
38
+ target_img_cv[:,:,0] = np.clip(target_img_cv[:,:,0] + (avg_l - np.mean(target_img_cv[:,:,0])), 0, 255)
39
+ target_img_cv[:,:,1] = np.clip(target_img_cv[:,:,1] + (avg_a - np.mean(target_img_cv[:,:,1])), 0, 255)
40
+ target_img_cv[:,:,2] = np.clip(target_img_cv[:,:,2] + (avg_b - np.mean(target_img_cv[:,:,2])), 0, 255)
41
+
42
+ return Image.fromarray(cv2.cvtColor(target_img_cv, cv2.COLOR_LAB2RGB))
43
+
44
+ def anim_frame_warp(img, angle, zoom, translation_x, translation_y):
45
+ width, height = img.size
46
+ center = (width // 2, height // 2)
47
+ matrix = cv2.getRotationMatrix2D(center, angle, zoom)
48
+ matrix[0, 2] += translation_x
49
+ matrix[1, 2] += translation_y
50
+ return Image.fromarray(cv2.warpAffine(np.array(img), matrix, (width, height), borderMode=cv2.BORDER_REPLICATE))
51
+
52
+ def lerp_frames(frame1, frame2, alpha):
53
+ arr1 = np.array(frame1).astype(np.float32)
54
+ arr2 = np.array(frame2).astype(np.float32)
55
+ blended = arr1 * (1 - alpha) + arr2 * alpha
56
+ return Image.fromarray(blended.astype(np.uint8))