检测角度并在Python中旋转图像

Wel*_*789 8 python

在python中检测角度并旋转图像

我想检测图(a)左侧的一个角度(即A)并将其旋转到正确的角度(即图b).此图像是答题纸.

我怎么能用Python做到这一点?

Mar*_*ans 22

您可以使用OpenCV HoughLines来检测图像中的线条.每条线的角度可以从这里找到:

import numpy as np
import cv2
import math
from scipy import ndimage

img_before = cv2.imread('rotate_me.png')

cv2.imshow("Before", img_before)    
key = cv2.waitKey(0)

img_gray = cv2.cvtColor(img_before, cv2.COLOR_BGR2GRAY)
img_edges = cv2.Canny(img_gray, 100, 100, apertureSize=3)
lines = cv2.HoughLinesP(img_edges, 1, math.pi / 180.0, 100, minLineLength=100, maxLineGap=5)

angles = []

for x1, y1, x2, y2 in lines[0]:
    cv2.line(img_before, (x1, y1), (x2, y2), (255, 0, 0), 3)
    angle = math.degrees(math.atan2(y2 - y1, x2 - x1))
    angles.append(angle)

median_angle = np.median(angles)
img_rotated = ndimage.rotate(img_before, median_angle)

print "Angle is {}".format(median_angle)
cv2.imwrite('rotated.jpg', img_rotated)  
Run Code Online (Sandbox Code Playgroud)

这会给你一个输出:

旋转图像

它显示检测到旋转的线条.计算的角度是:

Angle is 3.97938245268
Run Code Online (Sandbox Code Playgroud)

  • 您可以尝试研究 [`rotate`] 的 `cval` 参数(https://docs.scipy.org/doc/scipy/reference/ generated/scipy.ndimage.rotate.html#scipy-ndimage-rotate)功能。 (4认同)
  • 非常感谢马丁·埃文斯,它对我帮助很大。我想找到一个角度,这是一个很好的答案。 (2认同)