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

时间:2017-10-13 14:14:56

标签: python

Detect angle and rotate image in python

我想检测图(a)左侧的角度(即A)并将其旋转到正确的角度(即图b)。这张图片是答题纸。

我怎样才能在Python中执行此操作?

1 个答案:

答案 0 :(得分:9)

您可以将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)  

这会给你一个输出:

rotated image

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

Angle is 3.97938245268