-
Notifications
You must be signed in to change notification settings - Fork 0
/
spatial.py
132 lines (102 loc) · 2.72 KB
/
spatial.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""
Module defines methods to create and manage 2D affine transforms.
Contains 2D affine spatial transforms that can be
used to transform points in space. For example:
from numpy import radians
from spatial import point, rotation
p = point(1, 0)
r = rotation(radians(45))
po = r * p
Methods: point, cart2pol, pol2cart, translation, rotation,
scale, shear.
"""
from math import sin, cos, tan, hypot, atan2
from numpy.matlib import identity, ones
from numpy import radians
def point(x, y):
"""
2D affine point vector used in 2D spatial transformations. To use,
call the matrix '*' operator.
"""
m = ones((3, 1))
m[0] = x
m[1] = y
return m
def cart2pol(x, y):
"""
Converts x, y to polar coords.
x = position along x-axis.
y = position along y-axis.
returns r, theta
"""
if x == 0.0 and y == 0.0:
return 0, 0
r = hypot(x, y)
theta = atan2(y, x)
return r, theta
def pol2cart(r, theta):
"""
Converts r, theta to cartesian coords.
r = distance of a point from the origin.
theta = angle of the point with respect to the x-axis.
returns x, y
"""
x = r * cos(theta)
y = r * sin(theta)
return x, y
def translation(tx, ty):
"""
2D affine translation to be used in a matrix multiply operation
to translate a 2D affine point about the origin.
tx = translation along x axis.
ty = translation along y axis.
"""
m = identity(3)
m[0, 2] = tx
m[1, 2] = ty
return m
def rotation(theta):
"""
2D affine rotation to be used in a matrix multiply operation
to rotate a 2D affine point about the origin.
"""
m = identity(3)
s = sin(theta)
c = cos(theta)
m[0, 0] = c
m[0, 1] = -s
m[1, 0] = s
m[1, 1] = c
return m
def scale(sx, sy):
"""
2D affine scale transform to be used in a matrix multiply operation
to scale a 2D affine point about the origin.
sx = scale in x direction.
sx < 0.0 reflect about origin
sx = 1.0 (no scale),
0.0 < sx < 1.0 (reduce),
sx > 1.0 (increase),
sx = 0.0 (exception, undefined),
sy = scale in y direction.
sy < 0.0 reflect about origin
sy = 1.0 (no scale),
0.0 < sy < 1.0 (reduce),
sy > 1.0 (increase),
sy = 0 (exception, undefined)
"""
m = identity(3)
m[0, 0] = sx
m[1, 1] = sy
return m
def shear(hx, hy):
"""
2D affine shear to be used in a matrix multiply operation
to shear a 2D affine point about the origin.
hx = x axis shear angle, in radians clockwise from y axis,
hy = y axis shear angle, in radians counter-clockwise from x axis.
"""
m = identity(3)
m[0, 1] = tan(hx)
m[1, 0] = tan(hy)
return m