esXGray开发笔记:基于最小面积矩形的文本倾斜校正(python+opencv)

 

 

 1 import cv2
 2 import numpy as np
 3 
 4 # 定义一个函数来校正图像的倾斜
 5 def correct_skew(image):
 6     # 将图像转换为灰度图像
 7     gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
 8     # 使用高斯模糊来减少图像中的噪声
 9     blur = cv2.GaussianBlur(gray, (9, 9), 0)
10     # 使用自适应阈值化将图像转换为二值图像
11     thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,11,30)
12 
13     # 定义一个结构元素,用于图像的膨胀操作
14     kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
15     # 使用膨胀操作来连接断开的边缘
16     dilate = cv2.dilate(thresh, kernel, iterations=4)
17 
18     # 找到所有非零像素的坐标
19     coords = np.column_stack(np.where(dilate > 0))
20     # 使用最小面积矩形来计算旋转角度
21     angle = cv2.minAreaRect(coords)[-1]
22 
23     # 调整角度值
24     if angle < -45:
25         angle = -(90 + angle)
26     else:
27         angle = -angle
28 
29     # 获取图像的尺寸和中心点
30     (h, w) = image.shape[:2]
31     center = (w // 2, h // 2)
32     # 计算旋转矩阵
33     M = cv2.getRotationMatrix2D(center, angle, 1.0)
34     # 使用旋转矩阵来旋转图像
35     rotated = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
36 
37     # 返回校正后的图像
38     return rotated
39 
40 # 读取图像
41 image = cv2.imread('c:/users/eerso/desktop/1.png')
42 # 检查图像是否正确读取
43 if image is None:
44     print("Could not load image")
45     exit(-1)
46 # 调用函数来校正图像的倾斜
47 rotated = correct_skew(image)
48 # 显示原始图像
49 cv2.imshow('Src', image)
50 # 显示校正后的图像
51 cv2.imshow('Rotated', rotated)
52 # 等待用户按键,然后关闭窗口
53 cv2.waitKey(0)
54 cv2.destroyAllWindows()

 

代码已知问题:

  1. 背景复杂的图片识别不准确,需要先漂白、裁剪图片或者用其它方式获取主体区域;
  2. 长宽比过大的图片可能转正后部分图片超出原区域,实际应用时需要确定一下图片尺寸;
  3. 角度确定方法简略,有时会出现多转了90°(横向转成了竖向)。

最终放弃了这种算法,采用了基于直线检测的算法。

posted @ 2023-08-14 17:43  Moneky  阅读(180)  评论(0)    收藏  举报