【发布时间】:2018-03-25 17:02:18
【问题描述】:
【问题讨论】:
-
你的问题很广泛,它所属的主题不是标准python的一部分。我建议您阅读有关 opencv 的信息。同样为了您的声誉,您应该知道您的问题在 SO 中是题外话。
【问题讨论】:
您可以使用带有HoughLines 的OpenCV 来检测图像中的线条。每条线的角度可以从这里找到:
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:
cv2.line(img_before, (x1, y1), (x2, y2), (255, 0, 0), 3)
angle = math.degrees(math.atan2(y2 - y1, x2 - x1))
angles.append(angle)
cv2.imshow("Detected lines", img_before)
key = cv2.waitKey(0)
median_angle = np.median(angles)
img_rotated = ndimage.rotate(img_before, median_angle)
print(f"Angle is {median_angle:.04f}")
cv2.imwrite('rotated.jpg', img_rotated)
这会给你一个输出:
它显示检测到旋转的线条。计算的角度为:
Angle is 3.9793
如果您使用的是 Python 3.4 或更高版本,也可以使用statistics.median() 代替 numpy 版本。
【讨论】:
rotate 函数的 cval 参数。
for [[x1, y1, x2, y2]] in lines:吗?顺便说一句,如果你写 print(...) 它是 python3 兼容的 ;)