python - 图像的 3d 旋转

标签 python image-processing opencv

我正在尝试获取一些代码来对图像执行透视变换(在本例中为 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_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

关于python - 图像的 3d 旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9187387/

相关文章:

python - ipython:更改 PageDown/PageUp 以通过命令历史记录向后/向前移动

Python:你能逐个添加两个列表吗?

用于图像处理的 PHP 或 Python?

image-processing - 核心外重采样

python - 使用 open cv 和 python 更改图像标题以同时显示多个图像

python - 在 python + openCV 中使用网络摄像头的问题

matlab - 点云、聚类、 Blob 检测

Python for 循环优化

image-processing - 如何使用 labview 2011 从我的网络摄像头捕捉实时视频?

python - 如果不存在则创建文件,如果存在则不覆盖值