首页 > 解决方案 > 在opencv中使用3d旋转校正文档

问题描述

阅读这篇文章后,我可以使用以下代码在 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) != 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 轴上以负度重新旋转扭曲的图像,但我无法获得满意的结果。

  1. 原图:
    在此处输入图像描述

  2. 扭曲的图像在 x 轴上旋转 15 度,y 轴旋转 16 度,z 轴旋转 17 度: 在此处输入图像描述

  3. 重新旋转图像 2,x 轴为 -15 度,y 轴为 -16 度,z 轴为 -17 度: 在此处输入图像描述

但是第三张图像看起来仍然向 y 轴倾斜。

标签: pythonopencvimage-processing

解决方案


推荐阅读