-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
executable file
·60 lines (47 loc) · 1.96 KB
/
utils.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
from math import atan2, cos, sin, sqrt, pi
import numpy as np
import cv2 as cv
def drawAxis(img, p_, q_, colour, scale):
p = list(p_)
q = list(q_)
angle = atan2(p[1] - q[1], p[0] - q[0]) # angle in radians
hypotenuse = sqrt((p[1] - q[1]) * (p[1] - q[1]) + (p[0] - q[0]) * (p[0] - q[0]))
# Here we lengthen the arrow by a factor of scale
q[0] = p[0] - scale * hypotenuse * cos(angle)
q[1] = p[1] - scale * hypotenuse * sin(angle)
cv.line(img, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), colour, 2, cv.LINE_AA)
# create the arrow hooks
p[0] = q[0] + 9 * cos(angle + pi / 4)
p[1] = q[1] + 9 * sin(angle + pi / 4)
cv.line(img, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), colour, 2, cv.LINE_AA)
p[0] = q[0] + 9 * cos(angle - pi / 4)
p[1] = q[1] + 9 * sin(angle - pi / 4)
cv.line(img, (int(p[0]), int(p[1])), (int(q[0]), int(q[1])), colour, 2, cv.LINE_AA)
def getOrientation(pts, img, draw):
# Construct a buffer used by the pca analysis
sz = len(pts)
data_pts = np.empty((sz, 2), dtype=np.float64)
for i in range(data_pts.shape[0]):
data_pts[i, 0] = pts[i, 0, 0]
data_pts[i, 1] = pts[i, 0, 1]
# Perform PCA analysis
mean = np.empty((0))
mean, eigenvectors, eigenvalues = cv.PCACompute2(data_pts, mean)
# Store the center of the object
cntr = (int(mean[0, 0]), int(mean[0, 1]))
# Draw the principal components
cv.circle(img, cntr, 3, (42, 89, 247), -1)
p1 = (
cntr[0] + 0.02 * eigenvectors[0, 0] * eigenvalues[0, 0],
cntr[1] + 0.02 * eigenvectors[0, 1] * eigenvalues[0, 0]
)
p2 = (
cntr[0] - 0.02 * eigenvectors[1,0] * eigenvalues[1,0],
cntr[1] - 0.02 * eigenvectors[1,1] * eigenvalues[1,0]
)
if(draw):
drawAxis(img, cntr, p1, (91, 249, 77), 2)
drawAxis(img, cntr, p2, (190, 192, 91), 2)
# orientation in radians
angle = atan2(eigenvectors[0, 1], eigenvectors[0, 0])
return cntr, angle