Search code examples
pythonopencvmathgeometryhomography

How to get the rotation angle from findHomography?


I want to rotate the image without resorting to cv2.warpPerspective(). How to get angle from cv2.findHomography() function output?

It didn't help

# Find homography
H, mask = cv2.findHomography(points1, points2, cv2.RANSAC)

# for example my H:
array([[ 1.20001976e-01,  5.19205433e-04, -1.21739638e+01],
       [ 1.51272694e-03,  1.18686196e-01, -1.59772594e+01],
       [ 1.98308723e-06, -1.18197608e-07,  1.00000000e+00]])

# What should be the someFunction function?
angle = someFunction(H) # from 0 to 360

rotated = imutils.rotate(image, angle=angle)

Solution

  • If the transformation between the two set of points is a scale + rotation + translation, then the homography will simply be an affine matrix in which the 2x2 upper-left block is a scaled rotation. In this case, compute the angle using:

    angle = math.atan2(H[1,0], H[0,0])
    

    If some other kind of transformation can creep in (shearing, projective), it is safer to first perform an SVD decomposition of the 2x2 upper-left block to recover a rotation:

    u, _, vh = numpy.linalg.svd(H[0:2, 0:2])
    R = u @ vh
    angle = math.atan2(R[1,0], R[0,0])