c++利用opencv倾斜校正
时间: 2023-06-02 12:02:56 浏览: 121
OpenCV提供了一个名为“getRotationMatrix2D”的函数,该函数可以获取旋转矩阵,可以用它来校正倾斜的图像。下面是一个简单的例子:
```python
import cv2
import numpy as np
img = cv2.imread('skewed_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, 100) # 检测直线
# 找到最长的直线
max_len = 0
for line in lines:
rho, theta = line[0]
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))
len_line = np.sqrt((x2-x1)**2 + (y2-y1)**2)
if len_line > max_len:
max_len = len_line
longest_line = line
rho, theta = longest_line[0]
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) * 180 / np.pi # 计算角度
rows, cols, _ = img.shape
M = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1) # 获取旋转矩阵
dst = cv2.warpAffine(img, M, (cols, rows)) # 应用旋转矩阵
cv2.imshow('original', img)
cv2.imshow('corrected', dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在上述代码中,我们首先读取倾斜的图像,然后将其转换为灰度图像,并检测出边缘。接下来,我们使用霍夫变换检测出图像中的直线,并找到最长的直线。然后,我们计算出直线的角度,并使用该角度获取旋转矩阵。最后,我们应用旋转矩阵来校正倾斜的图像。
阅读全文
相关推荐



















