pythonpython-3.xopencvamazon-textract

How to calculate rotation angle of a rectangle with 4 points (x1,y1,.,x4,y4) in clock-wise direction, to make it straight or 0 degree


Given a polygon(tilted-rectangle) that represents a word region with 4- points ordered in a clockwise direction, how to identify the rotation angle to make it 0 degrees in viewing anlge to deskew the text?


Solution

  • I guess the rectangle looks like this?!

    enter image description here

    The red angle, let's call it alpha, is your rotation angle. Let's say the top left point is named A and top right is called B. The line from A to B is the hypotenuse of the red triangle which is as long as the width of the rectangle. The opposite cathetus is the right side of the red triangle which is as long as the difference between the y coordinates of A and B.

    The sine function is defined as the opposite cathetus divided by the hyptenuse.

    sin(alpha) = (y_A-y_B)/width -> alpha = sin^-1((y_A-y_B)/width)

    # I guess the coordinates are stored in a list (x1,y1,...,x4,y4) called coords
    y_A = coords[1]
    y_B = coords[3]
    
    op_cath = y_A - y_B
    
    import math
    alpha = math.asin(op_cath/width)
    

    To get the new coordinates (rotation).

    # new coordinates of A
    x_A = x_A*math.cos(alpha)-y_A*math.sin(alpha)
    y_A = x_A*math.sin(alpha)+y_A*math.cos(alpha)
    
    # repeat for each point
    

    (https://math.stackexchange.com/questions/2581058/rotating-rectangle-by-its-center)