在 Python 中检测角度并旋转图像 [英] Detect angle and rotate an image in Python
本文介绍了在 Python 中检测角度并旋转图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检测图 (a) 左侧的角度(即 A)并将其旋转到正确的角度(即图 b).此图片是答题纸.
如何在 Python 中执行此操作?
解决方案
你可以使用 OpenCV 和
它显示检测到旋转的线条.计算出的角度为:
角度为 3.9793
statistics.median()如果您使用的是 Python 3.4 或更高版本,也可以使用 code>
代替 numpy 版本.
I want to detect an angle (i.e, A) on the left hand side of figure (a) and rotate it in a correct one (i.e. figure b). This image is an answer sheet paper.
How can I do this in Python?
解决方案
You could use OpenCV with HoughLines
to detect lines in the image. The angle of each of the lines can be found from this:
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)
This would give you an output as:
It shows the lines that were detected to rotate. The angle calculated is:
Angle is 3.9793
statistics.median()
could also be used instead of the numpy version if you are using Python 3.4 or later.
这篇关于在 Python 中检测角度并旋转图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文