Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/HeadPose/headPose.py
3118 views
1
#!/usr/bin/env python
2
3
import cv2
4
import numpy as np
5
6
# Read Image
7
im = cv2.imread("headPose.jpg");
8
size = im.shape
9
10
#2D image points. If you change the image, you need to change vector
11
image_points = np.array([
12
(359, 391), # Nose tip
13
(399, 561), # Chin
14
(337, 297), # Left eye left corner
15
(513, 301), # Right eye right corne
16
(345, 465), # Left Mouth corner
17
(453, 469) # Right mouth corner
18
], dtype="double")
19
20
# 3D model points.
21
model_points = np.array([
22
(0.0, 0.0, 0.0), # Nose tip
23
(0.0, -330.0, -65.0), # Chin
24
(-225.0, 170.0, -135.0), # Left eye left corner
25
(225.0, 170.0, -135.0), # Right eye right corne
26
(-150.0, -150.0, -125.0), # Left Mouth corner
27
(150.0, -150.0, -125.0) # Right mouth corner
28
29
])
30
31
32
# Camera internals
33
34
focal_length = size[1]
35
center = (size[1]/2, size[0]/2)
36
camera_matrix = np.array(
37
[[focal_length, 0, center[0]],
38
[0, focal_length, center[1]],
39
[0, 0, 1]], dtype = "double"
40
)
41
42
print "Camera Matrix :\n {0}".format(camera_matrix);
43
44
dist_coeffs = np.zeros((4,1)) # Assuming no lens distortion
45
(success, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, camera_matrix, dist_coeffs, flags=cv2.SOLVEPNP_ITERATIVE)
46
47
print "Rotation Vector:\n {0}".format(rotation_vector)
48
print "Translation Vector:\n {0}".format(translation_vector)
49
50
51
# Project a 3D point (0, 0, 1000.0) onto the image plane.
52
# We use this to draw a line sticking out of the nose
53
54
55
(nose_end_point2D, jacobian) = cv2.projectPoints(np.array([(0.0, 0.0, 1000.0)]), rotation_vector, translation_vector, camera_matrix, dist_coeffs)
56
57
for p in image_points:
58
cv2.circle(im, (int(p[0]), int(p[1])), 3, (0,0,255), -1)
59
60
61
p1 = ( int(image_points[0][0]), int(image_points[0][1]))
62
p2 = ( int(nose_end_point2D[0][0][0]), int(nose_end_point2D[0][0][1]))
63
64
cv2.line(im, p1, p2, (255,0,0), 2)
65
66
67
# Display image
68
cv2.imshow("Output", im);
69
cv2.waitKey(0);
70
71