Created
November 5, 2019 01:03
-
-
Save ALevitskyy/88aa02747e0da5b7950b79c56b60b2e7 to your computer and use it in GitHub Desktop.
Convert CV2 extrinsic to Blender camera.object.location and camera.object.rotation_euler parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import cv2 | |
import numpy as np | |
def isRotationMatrix(R): | |
Rt = np.transpose(R) | |
shouldBeIdentity = np.dot(Rt, R) | |
I = np.identity(3, dtype=R.dtype) | |
n = np.linalg.norm(I - shouldBeIdentity) | |
return n < 1e-6 | |
# Calculates rotation matrix to euler angles | |
# The result is the same as MATLAB except the order | |
# of the euler angles ( x and z are swapped ). | |
def rotationMatrixToEulerAngles(R): | |
assert isRotationMatrix(R) | |
sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0]) | |
singular = sy < 1e-6 | |
if not singular: | |
x = math.atan2(R[2, 1], R[2, 2]) | |
y = math.atan2(-R[2, 0], sy) | |
z = math.atan2(R[1, 0], R[0, 0]) | |
else: | |
x = math.atan2(-R[1, 2], R[1, 1]) | |
y = math.atan2(-R[2, 0], sy) | |
z = 0 | |
return np.array([x, y, z]) | |
def extrinsic_to_blender(rotation, translation): | |
adjustment_mat = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]]) | |
rotataion_matrix, _ = cv2.Rodrigues(rotation) | |
blender_camera_location = -rotataion_matrix.T @ translation | |
blender_camera_rotation = rotationMatrixToEulerAngles( | |
rotataion_matrix.T @ adjustment_mat | |
) | |
return blender_camera_rotation, blender_camera_location |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment