图像的3D旋转

11

我正在尝试获取一些代码,可以对图像执行透视变换(在这种情况下是3D旋转)。

import os.path
import numpy as np
import cv

def rotation(angle, axis):
    return np.eye(3) + np.sin(angle) * skew(axis) \
               + (1 - np.cos(angle)) * skew(axis).dot(skew(axis))

def skew(vec):
    return np.array([[0, -vec[2], vec[1]],
                     [vec[2], 0, -vec[0]],
                     [-vec[1], vec[0], 0]])

def rotate_image(imgname_in, angle, axis, imgname_out=None):
    if imgname_out is None:
        base, ext = os.path.splitext(imgname_in)
        imgname_out = base + '-out' + ext
    img_in = cv.LoadImage(imgname_in)
    img_size = cv.GetSize(img_in)
    img_out = cv.CreateImage(img_size, img_in.depth, img_in.nChannels)
    transform = rotation(angle, axis)
    cv.WarpPerspective(img_in, img_out, cv.fromarray(transform))
    cv.SaveImage(imgname_out, img_out)

当我绕z轴旋转时,一切都按预期工作,但围绕x或y轴旋转似乎完全出错了。我需要旋转的角度尽可能小,才能开始获得看起来合理的结果。有什么想法可能出了问题?

2个回答

30

首先,构建旋转矩阵,其形式为

    [cos(theta)  -sin(theta)  0]
R = [sin(theta)   cos(theta)  0]
    [0            0           1]

应用这个坐标变换可以让你围绕原点旋转。

如果你想围绕图像中心旋转,你需要先将图像中心移动到原点,然后应用旋转,最后再将所有东西移回去。你可以使用一个平移矩阵来实现:

    [1  0  -image_width/2]
T = [0  1  -image_height/2]
    [0  0   1]

平移、旋转和逆平移的变换矩阵如下:

H = inv(T) * R * T

我需要花点时间思考如何将斜矩阵与三维变换联系起来。我认为最简单的方法是设置一个四维变换矩阵,然后将其投影回二维齐次坐标系。但目前来说,斜矩阵的一般形式如下:

    [x_scale 0       0]
S = [0       y_scale 0]
    [x_skew  y_skew  1]

x_skewy_skew的值通常非常小(1e-3或更小)。

以下是代码:

from skimage import data, transform
import numpy as np
import matplotlib.pyplot as plt

img = data.camera()

theta = np.deg2rad(10)
tx = 0
ty = 0

S, C = np.sin(theta), np.cos(theta)

# Rotation matrix, angle theta, translation tx, ty
H = np.array([[C, -S, tx],
              [S,  C, ty],
              [0,  0, 1]])

# Translation matrix to shift the image center to the origin
r, c = img.shape
T = np.array([[1, 0, -c / 2.],
              [0, 1, -r / 2.],
              [0, 0, 1]])

# Skew, for perspective
S = np.array([[1, 0, 0],
              [0, 1.3, 0],
              [0, 1e-3, 1]])

img_rot = transform.homography(img, H)
img_rot_center_skew = transform.homography(img, S.dot(np.linalg.inv(T).dot(H).dot(T)))

f, (ax0, ax1, ax2) = plt.subplots(1, 3)
ax0.imshow(img, cmap=plt.cm.gray, interpolation='nearest')
ax1.imshow(img_rot, cmap=plt.cm.gray, interpolation='nearest')
ax2.imshow(img_rot_center_skew, cmap=plt.cm.gray, interpolation='nearest')
plt.show()

并且输出:

Rotations of cameraman around origin and center+skew


0

我不理解你构建旋转矩阵的方式,对我来说似乎相当复杂。通常情况下,它会通过构建一个零矩阵,在不需要的轴上放置1,并在两个使用的维度中放置常见的sincos-cossin。然后将所有这些相乘。

你从哪里得到了那个np.eye(3) + np.sin(angle) * skew(axis) + (1 - np.cos(angle)) * skew(axis).dot(skew(axis))构造物?

尝试从基本构件构建投影矩阵。构建旋转矩阵相当容易,“rotationmatrix dot skewmatrix”应该有效。

但是你可能需要注意旋转中心。您的图像可能被放置在z轴上虚拟位置1处,因此通过x或y旋转,它会移动一点。 因此,您需要使用平移使z变为0,然后旋转,最后再平移回去。(在仿射坐标中的平移矩阵也很简单。请参见维基百科:https://en.wikipedia.org/wiki/Transformation_matrix


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接