opencv+python倾斜文本图片矫正
时间: 2025-06-29 07:17:16 浏览: 12
### 使用 OpenCV 和 Python 进行倾斜文本图像校正
对于倾斜的文本图像,可以采用霍夫变换检测文档边缘并计算旋转角度来实现矫正。具体方法如下:
#### 导入必要的库
首先导入所需的库文件[^1]。
```python
import cv2
import numpy as np
from skimage import measure
```
#### 预处理输入图像
读取待处理的图片,并将其转换成灰度图以便后续操作[^1]。
```python
image = cv2.imread('skew_image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
```
#### 边缘检测与轮廓提取
应用高斯模糊减少噪声干扰,再通过Canny算子获取二值化后的边界信息;利用`findContours()`函数查找所有封闭区域中的最大矩形框作为目标对象[^1]。
```python
blurred = cv2.GaussianBlur(gray, (9, 9), 0)
edged = cv2.Canny(blurred, 50, 200, 255)
contours, _ = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)[:5]
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
doc_cnt = approx
break
```
#### 计算最小外接矩阵的角度差值
调用`minAreaRect()`获得四个顶点坐标构成的多边形及其方向角θ,当θ位于(-45°,-90°]区间内时需调整为正值表示顺时针偏转程度[^1]。
```python
rect = cv2.minAreaRect(doc_cnt)
angle = rect[-1]
if angle < -45:
angle = -(90 + angle)
else:
angle = -angle
```
#### 图像仿射变换完成最终校准
构建围绕中心点逆向旋转变换矩阵M,之后借助`warpAffine()`执行实际的空间映射过程得到直立状态下的文字影像资料[^1]。
```python
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h),
flags=cv2.INTER_CUBIC,
borderMode=cv2.BORDER_REPLICATE)
```
最后保存修正过的结果至本地磁盘中[^1]。
```python
cv2.imwrite("corrected_skew.png", rotated)
```
阅读全文
相关推荐


















