headPose.py 2.4 KB

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