Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/core/mathlib/__init__.py
628 views
1
import math
2
3
import cv2
4
import numpy as np
5
import numpy.linalg as npla
6
7
from .umeyama import umeyama
8
9
10
def get_power_of_two(x):
11
i = 0
12
while (1 << i) < x:
13
i += 1
14
return i
15
16
def rotationMatrixToEulerAngles(R) :
17
sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
18
singular = sy < 1e-6
19
if not singular :
20
x = math.atan2(R[2,1] , R[2,2])
21
y = math.atan2(-R[2,0], sy)
22
z = math.atan2(R[1,0], R[0,0])
23
else :
24
x = math.atan2(-R[1,2], R[1,1])
25
y = math.atan2(-R[2,0], sy)
26
z = 0
27
return np.array([x, y, z])
28
29
def polygon_area(x,y):
30
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
31
32
def rotate_point(origin, point, deg):
33
"""
34
Rotate a point counterclockwise by a given angle around a given origin.
35
36
The angle should be given in radians.
37
"""
38
ox, oy = origin
39
px, py = point
40
41
rad = deg * math.pi / 180.0
42
qx = ox + math.cos(rad) * (px - ox) - math.sin(rad) * (py - oy)
43
qy = oy + math.sin(rad) * (px - ox) + math.cos(rad) * (py - oy)
44
return np.float32([qx, qy])
45
46
def transform_points(points, mat, invert=False):
47
if invert:
48
mat = cv2.invertAffineTransform (mat)
49
points = np.expand_dims(points, axis=1)
50
points = cv2.transform(points, mat, points.shape)
51
points = np.squeeze(points)
52
return points
53
54
55
def transform_mat(mat, res, tx, ty, rotation, scale):
56
"""
57
transform mat in local space of res
58
scale -> translate -> rotate
59
60
tx,ty float
61
rotation int degrees
62
scale float
63
"""
64
65
66
lt, rt, lb, ct = transform_points ( np.float32([(0,0),(res,0),(0,res),(res / 2, res/2) ]),mat, True)
67
68
hor_v = (rt-lt).astype(np.float32)
69
hor_size = npla.norm(hor_v)
70
hor_v /= hor_size
71
72
ver_v = (lb-lt).astype(np.float32)
73
ver_size = npla.norm(ver_v)
74
ver_v /= ver_size
75
76
bt_diag_vec = (rt-ct).astype(np.float32)
77
half_diag_len = npla.norm(bt_diag_vec)
78
bt_diag_vec /= half_diag_len
79
80
tb_diag_vec = np.float32( [ -bt_diag_vec[1], bt_diag_vec[0] ] )
81
82
rt = ct + bt_diag_vec*half_diag_len*scale
83
lb = ct - bt_diag_vec*half_diag_len*scale
84
lt = ct - tb_diag_vec*half_diag_len*scale
85
86
rt[0] += tx*hor_size
87
lb[0] += tx*hor_size
88
lt[0] += tx*hor_size
89
rt[1] += ty*ver_size
90
lb[1] += ty*ver_size
91
lt[1] += ty*ver_size
92
93
rt = rotate_point(ct, rt, rotation)
94
lb = rotate_point(ct, lb, rotation)
95
lt = rotate_point(ct, lt, rotation)
96
97
return cv2.getAffineTransform( np.float32([lt, rt, lb]), np.float32([ [0,0], [res,0], [0,res] ]) )
98
99