rotm2euler.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #!/usr/bin/env python
  2. # Copyright (c) 2016 Satya Mallick <spmallick@learnopencv.com>
  3. # All rights reserved. No warranty, explicit or implicit, provided.
  4. import cv2
  5. import numpy as np
  6. import math
  7. import random
  8. # Checks if a matrix is a valid rotation matrix.
  9. def isRotationMatrix(R) :
  10. Rt = np.transpose(R)
  11. shouldBeIdentity = np.dot(Rt, R)
  12. I = np.identity(3, dtype = R.dtype)
  13. n = np.linalg.norm(I - shouldBeIdentity)
  14. return n < 1e-6
  15. # Calculates rotation matrix to euler angles
  16. # The result is the same as MATLAB except the order
  17. # of the euler angles ( x and z are swapped ).
  18. def rotationMatrixToEulerAngles(R) :
  19. assert(isRotationMatrix(R))
  20. sy = math.sqrt(R[0,0] * R[0,0] + R[1,0] * R[1,0])
  21. singular = sy < 1e-6
  22. if not singular :
  23. x = math.atan2(R[2,1] , R[2,2])
  24. y = math.atan2(-R[2,0], sy)
  25. z = math.atan2(R[1,0], R[0,0])
  26. else :
  27. x = math.atan2(-R[1,2], R[1,1])
  28. y = math.atan2(-R[2,0], sy)
  29. z = 0
  30. return np.array([x, y, z])
  31. # Calculates Rotation Matrix given euler angles.
  32. def eulerAnglesToRotationMatrix(theta) :
  33. R_x = np.array([[1, 0, 0 ],
  34. [0, math.cos(theta[0]), -math.sin(theta[0]) ],
  35. [0, math.sin(theta[0]), math.cos(theta[0]) ]
  36. ])
  37. R_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1]) ],
  38. [0, 1, 0 ],
  39. [-math.sin(theta[1]), 0, math.cos(theta[1]) ]
  40. ])
  41. R_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0],
  42. [math.sin(theta[2]), math.cos(theta[2]), 0],
  43. [0, 0, 1]
  44. ])
  45. R = np.dot(R_z, np.dot( R_y, R_x ))
  46. return R
  47. if __name__ == '__main__' :
  48. # Randomly generate Euler angles
  49. e = np.random.rand(3) * math.pi * 2 - math.pi
  50. # Calculate rotation matrix
  51. R = eulerAnglesToRotationMatrix(e)
  52. # Calculate Euler angles from rotation matrix
  53. e1 = rotationMatrixToEulerAngles(R)
  54. # Calculate rotation matrix
  55. R1 = eulerAnglesToRotationMatrix(e1)
  56. # Note e and e1 will be the same a lot of times
  57. # but not always. R and R1 should be the same always.
  58. print "\nInput Euler angles :\n{0}".format(e)
  59. print "\nR :\n{0}".format(R)
  60. print "\nOutput Euler angles :\n{0}".format(e1)
  61. print "\nR1 :\n{0}".format(R1)