Python图像旋转角度计算

标签 python opencv geometry atan2 radians

我正在开发一个应用程序,它首先需要稍微旋转图像以消除歪斜。

我检测到图像上两点 (x1, y1) 和 (x2,y2) 之间有一条垂直线。垂直线并不完全垂直 - 第二个 x 坐标略小于或略大于顶部 x,因此该线具有坡度。

我正在尝试计算线的倾斜角度,以便我可以旋转图像,然后重新检测线,使其完全垂直。为此,我在 Python 中使用 OpenCV。

不幸的是,我在计算直线的斜率时遇到问题,因此图像的旋转不准确。

我检测图像中垂直线斜率的函数如下:

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

我旋转图像以使线条可以垂直的代码如下:

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))

但是旋转角度却显示为 249 度、89 度等,而实际上它们应该只有几度。

如果有人可以帮助我找到这个问题的解决方案,以便我可以正确纠正图像的倾斜,我将不胜感激。

最佳答案

我相信您正在找到与您想要的角度互补的角度。

一条几乎垂直的线相对于 y 轴的角度非常小,但相对于 x 轴的角度接近 90 度。

将线段视为直角三角形的斜边。它相对于 x 轴形成的角度为 atan((y2-y1)/(x2-x1))。相对于 y 轴的角度,我认为你想要旋转的角度应该是 atan((x2-x1)/(y2-y1))

关于Python图像旋转角度计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27672269/

相关文章:

python - 在非空行上过滤数据框

具有格式化程序的 Python 日志记录模块导致 AttributeError

python - Django shell_plus : How to access Jupyter notebook in Docker Container

java - 使用 JavaCV 计算 Homography 的 CvPoint2D32f 到 cvMat 的列表

python - 使用两个标志OpenCv的calibrateCamera函数时出错

python - Matplotlib - 提取 3D 多边形图的 2D 轮廓

python - 如何在 ModelForm 中使用 forms.ChoiceField()?

python - 无法在 Python OpenCV v4.20 中使用 SIFT

image-processing - 解释霍夫变换

c# - 计算旋转时相对于其他点的点位置 - C# XNA