Python cv2.warpPerspective 3D旋转

时间:2017-06-19 16:22:04

标签: python opencv image-processing

我在cv2.warpPerspective函数中理解旋转矩阵时遇到问题。我写了这个程序:

import cv2, math
import numpy as np

def translation_mat(dx, dy):
    return np.array([1,0,dx,   0,1,dy,   0,0,1]).reshape((3,3))

def anglesToRotationMatrix(angles, image_size) :
    # convert angle in radians
    rangle = np.deg2rad(angles)
    # calculate middle of image
    t1 = translation_mat(-image_size[1]/2, -image_size[0]/2)
    t2 = translation_mat( image_size[1]/2, image_size[0]/2 )

    R_x = np.array([[1,         0,                   0                     ],
                    [0,         math.cos(rangle[0]),  -math.sin(rangle[0]) ],
                    [0,         math.sin(rangle[0]),  math.cos(rangle[0])  ]
                    ])

    R_y = np.array([[math.cos(rangle[1]) ,   0,      math.sin(rangle[1])   ],
                    [0                   ,   1,      0                     ],
                    [-math.sin(rangle[1]),   0,      math.cos(rangle[1])   ]
                    ])

    R_z = np.array([[math.cos(rangle[2]),    -math.sin(rangle[2]),        0],
                    [math.sin(rangle[2]),    math.cos(rangle[2]) ,        0],
                    [0                  ,    0                   ,        1]
                    ])

    R = np.dot( t2.dot(R_z.dot(t1)), np.dot( t2.dot(R_y.dot(t1)), t2.dot(R_x.dot(t1)) ) )

    return R

def rotateImageByDegrees(input_image, angles) :
    # calculate warp matrix
    warp_matrix = anglesToRotationMatrix(angles, input_image.shape)
    print warp_matrix
    #im_aligned = cv2.warpPerspective (input_image, warp_matrix, (input_image.shape[1], input_image.shape[0]), flags=cv2.INTER_LINEAR, borderValue=(255, 255, 255) )
    rotated_image = cv2.warpPerspective (input_image, warp_matrix, (input_image.shape[1], input_image.shape[0]), flags=cv2.INTER_LINEAR )
    return rotated_image

if __name__ == '__main__':
    im =  cv2.imread("Lenna.png", cv2.IMREAD_GRAYSCALE);
    im_aligned = rotateImageByDegrees(im, [-0.1, 0.0,   0])

    # Show final output
    cv2.imshow("original", im)
    cv2.imshow("rotated", im_aligned)
    cv2.waitKey(0)

我期待函数rotateImageByDegrees(im,[ - 0.10,0.0,0))应该只在一个轴上以非常小的角度旋转图像,但是在图像is quite big中更改。但是对于轴Z,一切正常(i.e. image is rotated by 45 degrees without any problems)。我错在哪里?

0 个答案:

没有答案