mtwohey2 commited on
Commit
18f585c
·
verified ·
1 Parent(s): c1e82ac

Create utils/util.py

Browse files
Files changed (1) hide show
  1. utils/util.py +74 -0
utils/util.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (2025) Bytedance Ltd. and/or its affiliates
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import numpy as np
15
+
16
+ def compute_scale_and_shift(prediction, target, mask, scale_only=False):
17
+ if scale_only:
18
+ return compute_scale(prediction, target, mask), 0
19
+ else:
20
+ return compute_scale_and_shift_full(prediction, target, mask)
21
+
22
+
23
+ def compute_scale(prediction, target, mask):
24
+ # system matrix: A = [[a_00, a_01], [a_10, a_11]]
25
+ prediction = prediction.astype(np.float32)
26
+ target = target.astype(np.float32)
27
+ mask = mask.astype(np.float32)
28
+
29
+ a_00 = np.sum(mask * prediction * prediction)
30
+ a_01 = np.sum(mask * prediction)
31
+ a_11 = np.sum(mask)
32
+
33
+ # right hand side: b = [b_0, b_1]
34
+ b_0 = np.sum(mask * prediction * target)
35
+
36
+ x_0 = b_0 / (a_00 + 1e-6)
37
+
38
+ return x_0
39
+
40
+ def compute_scale_and_shift_full(prediction, target, mask):
41
+ # system matrix: A = [[a_00, a_01], [a_10, a_11]]
42
+ prediction = prediction.astype(np.float32)
43
+ target = target.astype(np.float32)
44
+ mask = mask.astype(np.float32)
45
+
46
+ a_00 = np.sum(mask * prediction * prediction)
47
+ a_01 = np.sum(mask * prediction)
48
+ a_11 = np.sum(mask)
49
+
50
+ b_0 = np.sum(mask * prediction * target)
51
+ b_1 = np.sum(mask * target)
52
+
53
+ x_0 = 1
54
+ x_1 = 0
55
+
56
+ det = a_00 * a_11 - a_01 * a_01
57
+
58
+ if det != 0:
59
+ x_0 = (a_11 * b_0 - a_01 * b_1) / det
60
+ x_1 = (-a_01 * b_0 + a_00 * b_1) / det
61
+
62
+ return x_0, x_1
63
+
64
+
65
+ def get_interpolate_frames(frame_list_pre, frame_list_post):
66
+ assert len(frame_list_pre) == len(frame_list_post)
67
+ min_w = 0.0
68
+ max_w = 1.0
69
+ step = (max_w - min_w) / (len(frame_list_pre)-1)
70
+ post_w_list = [min_w] + [i * step for i in range(1,len(frame_list_pre)-1)] + [max_w]
71
+ interpolated_frames = []
72
+ for i in range(len(frame_list_pre)):
73
+ interpolated_frames.append(frame_list_pre[i] * (1-post_w_list[i]) + frame_list_post[i] * post_w_list[i])
74
+ return interpolated_frames