简体   繁体   中英

Python angle calculation for image rotation

I am working on an application which first needs to rotate an image slightly in order to deskew it.

I have detected a vertical line down the image between two points (x1, y1) and (x2,y2). The vertical line is not entirely vertical - the second x coordinate is slightly less or slightly more than the top x and therefore the line has a slope.

I am trying to calculate the angle of the slope of the line so that I can rotate the image and then re-detect the line so that it is perfectly vertical. I am using OpenCV in Python for this.

Unfortunately I am having problems calculating the slope of the line and the rotation of the image is therefore inaccurate.

My function to detect the slope of the vertical line in the image is as follows:

def find_vert_angles(vertical_line_candidates, vertical_line_candidates2, roi_x_coordinates,      roi_x_coordinates2):
line_angles_radians = []

for line_x, line_x2 in itertools.izip(vertical_line_candidates, vertical_line_candidates2):
    x_diff = line_x2 - line_x
    y_diff =  roi_x_coordinates[1][1] - roi_x_coordinates[0][1]

    if x_diff != 0:
        slope = y_diff / x_diff
        angle_in_radians = atan(slope)
        line_angles_radians.append(angle_in_radians)
    else:
        line_angles_radians.append(0)

return line_angles_radians

My code to rotate the image so that the line can be vertical is as follows:

skew_angle = degrees(vert_angle[1])
print "Detected skew angle is " + str(skew_angle) + " degrees"
warp = cv2.getRotationMatrix2D((img_width/2,img_height/2),skew_angle,1)
image = cv2.warpAffine(image,warp,(img_width,img_height))

But the angles of rotation are coming out as 249 degrees, 89 degrees etc. when they should just be a few degrees each way.

If anyone can help me find a solution to this problem so that I can correct the skew of the image correctly, that would be much appreciated.

I believe you're finding the angle that's complementary to the one you want.

A nearly vertical line will have a very small angle with respect to the y-axis, but a near 90-degree angle with respect to the x-axis.

Consider your line segment to be the hypotenuse of a right triangle. The angle it forms with respect to the x-axis is atan((y2-y1)/(x2-x1)). The angle with respect to the y-axis, which I think is what you want to rotate should be atan((x2-x1)/(y2-y1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM