Specify an origin to warpPerspective() function in OpenCV 2.x

前端 未结 3 1959
执念已碎
执念已碎 2020-12-06 23:31

I try to specify a different origin for the warpPerspective() function than the basic (0,0), in order to apply the transform independently of the support image size. I added

3条回答
  •  生来不讨喜
    2020-12-06 23:54

    A much simpler and cleaner solution is to modify the perspective transformation. You can do a translation which moves the origin to the desired position, then do the perspective transformation and finally do the inverse translation.

    Here is a small example program in python, which rotates an image by 45 degrees around the point(100, 100):

    import cv2
    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 main():
        img = cv2.imread(r"pigeon.png", cv2.IMREAD_GRAYSCALE)
    
        # a simple rotation by 45 degrees
    rot = np.array([np.sin(np.pi/4), -np.cos(np.pi/4), 0, np.cos(np.pi/4), np.sin(np.pi/4), 0, 0, 0, 1]).reshape((3,3))
        t1 = translation_mat(-100, -100)
        t2 = translation_mat(100, 100)
        rot_shifted = t2.dot(rot.dot(t1))
        size = (img.shape[1], img.shape[0])
    
        img1 = cv2.warpPerspective(img, rot, size)
        img2 = cv2.warpPerspective(img, rot_shifted, size)
    
        cv2.imshow("Original image", img)
        cv2.imshow("Rotated around (0,0)", img1)
        cv2.imshow("Rotated around(100, 100)", img2)
        cv2.waitKey(0)
    
    
    if __name__ == '__main__':
        main()
    

    Not that you read the order of transformations from right to left.

    rot_shifted = t2.dot(rot.dot(t1))
    

    will apply t1 first, then rot, and then t2.

提交回复
热议问题