Python 在opencv上使用三维旋转更正文档
阅读后,我可以使用以下代码在x、y、z轴上制作旋转图像:Python 在opencv上使用三维旋转更正文档,python,opencv,image-processing,Python,Opencv,Image Processing,阅读后,我可以使用以下代码在x、y、z轴上制作旋转图像: import numpy as np import cv2 def get_3d_rotation_matrix(width, height, theta, phi, gamma, dx, dy, dz): w, h = width, height d = np.sqrt(w ** 2 + h ** 2) focal = f = d / (2 * np.sin(gamma) if np.sin(gamma) !
import numpy as np
import cv2
def get_3d_rotation_matrix(width, height, theta, phi, gamma, dx, dy, dz):
w, h = width, height
d = np.sqrt(w ** 2 + h ** 2)
focal = f = d / (2 * np.sin(gamma) if np.sin(gamma) != 0 else 1)
dz = focal
# Projection 2D -> 3D matrix
A1 = np.array([[1, 0, -w / 2],
[0, 1, -h / 2],
[0, 0, 1],
[0, 0, 1]])
# Rotation matrices around the X, Y, and Z axis
RX = np.array([[1, 0, 0, 0],
[0, np.cos(theta), -np.sin(theta), 0],
[0, np.sin(theta), np.cos(theta), 0],
[0, 0, 0, 1]])
RY = np.array([[np.cos(phi), 0, -np.sin(phi), 0],
[0, 1, 0, 0],
[np.sin(phi), 0, np.cos(phi), 0],
[0, 0, 0, 1]])
RZ = np.array([[np.cos(gamma), -np.sin(gamma), 0, 0],
[np.sin(gamma), np.cos(gamma), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
# Composed rotation matrix with (RX, RY, RZ)
R = np.dot(np.dot(RX, RY), RZ)
# Translation matrix
T = np.array([[1, 0, 0, dx],
[0, 1, 0, dy],
[0, 0, 1, dz],
[0, 0, 0, 1]])
# Projection 3D -> 2D matrix
A2 = np.array([[f, 0, w / 2, 0],
[0, f, h / 2, 0],
[0, 0, 1, 0]])
# Final transformation matrix
return np.dot(A2, np.dot(T, np.dot(R, A1)))
def get_image_3d_rotated(image, theta, phi, gamma, dx, dy, dz):
height, width, _ = image.shape
rtheta, rphi, rgamma = np.deg2rad(theta), np.deg2rad(phi), np.deg2rad(gamma)
mat = get_3d_rotation_matrix(width, height, rtheta, rphi, rgamma, dx, dy, dz)
return cv2.warpPerspective(image.copy(), mat, (width, height))
if __name__ == '__main__':
image = cv2.imread('1.jpg')
rotated_img = get_image_3d_rotated(image, 15, 16, 17, 0, 0, 0)
我的问题是,如果我知道图像的3d旋转角度,有没有办法得到像原始图像一样的校正图像?我尝试在x、y、z轴上以负角度重新旋转扭曲图像,但没有得到满意的结果
但第三幅图像看起来仍然向y轴倾斜。我还没有深入研究,但问题可能与旋转不可交换这一事实有关。所以,如果你做了
res=A(B(C(img))
doAinv(Binv(Cinv(res)))
@user\n你的建议是有道理的,但是代码中的投影矩阵A1,A2是4x3,3x4矩阵,所以没有逆矩阵。如何解决呢?