python图像边缘检测倾斜校正代码
时间: 2023-07-22 19:50:50 浏览: 93
以下是使用OpenCV库进行图像边缘检测和倾斜校正的Python代码示例:
```python
import cv2
import numpy as np
# 读取原始图像
img = cv2.imread('image.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 边缘检测
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
# 获取直线
lines = cv2.HoughLines(edges, 1, np.pi/180, 200)
# 计算角度
angles = []
for line in lines:
for rho, theta in line:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
angle = np.arctan2(y2-y1, x2-x1)
angles.append(angle)
# 计算平均角度
avg_angle = np.mean(angles)
# 旋转校正
rows, cols = img.shape[:2]
M = cv2.getRotationMatrix2D((cols/2, rows/2), avg_angle*180/np.pi, 1)
corrected_img = cv2.warpAffine(img, M, (cols, rows))
# 显示结果
cv2.imshow('Original Image', img)
cv2.imshow('Corrected Image', corrected_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
代码中使用Canny边缘检测和Hough变换检测直线,计算直线角度,再根据平均角度旋转校正原始图像。
阅读全文