我正在尝试获取一些代码来对图像执行透视变换(在本例中为 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 轴旋转似乎完全关闭。在开始获得看起来完全合理的结果之前,我需要旋转小至 pi/200 的角度。知道哪里出了问题吗?
最佳答案
首先,构建形式为的旋转矩阵
[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
我将不得不考虑一下如何将偏斜矩阵与 3D 变换相关联。我希望最简单的方法是设置一个 4D 变换矩阵,然后将其投影回 2D 齐次坐标。但是现在,偏斜矩阵的一般形式:
[x_scale 0 0]
S = [0 y_scale 0]
[x_skew y_skew 1]
x_skew
和 y_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()
输出:
关于python - 图像的 3d 旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9187387/