opencv-70-形态学应用(使用基本梯度实现轮廓分析)

知识点

基于形态学梯度实现图像二值化,进行文本结构分析是OCR识别中常用的处理手段之一,这种好处比简单的二值化对图像有更好的分割效果,主要步骤如下:

  1. 图像形态学梯度
  2. 灰度
  3. 全局阈值二值化
  4. 轮廓分析

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 形态学应用(使用基本梯度实现轮廓分析)
*/
int main() {
Mat src = imread("../images/address.jpg");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

Mat basic, gray, binary;
// 基本梯度
Mat se = getStructuringElement(MORPH_RECT, Size(3, 3));
morphologyEx(src, basic, MORPH_GRADIENT, se);

// 二值化
cvtColor(basic, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);

// 膨胀
se = getStructuringElement(MORPH_RECT, Size(1, 5));
morphologyEx(binary, binary, MORPH_DILATE, se);

// 轮廓绘制
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(binary, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (size_t c = 0; c < contours.size(); c++) {
Rect rect = boundingRect(contours[c]);
double area = contourArea(contours[c]);
if (area < 200) {
continue;
}
int h = rect.height;
int w = rect.width;
if (h > (3 * w) || h < 20) {
continue;
}
rectangle(src, rect, Scalar(0, 0, 255));
}
imshow("result", src);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import cv2 as cv

src = cv.imread("D:/images/kd02.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

# 形态学梯度 - 基本梯度
se = cv.getStructuringElement(cv.MORPH_RECT, (3, 3), (-1, -1))
basic = cv.morphologyEx(src, cv.MORPH_GRADIENT, se)
cv.imshow("basic gradient", basic)

gray = cv.cvtColor(basic, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
cv.imshow("binary", binary)

se = cv.getStructuringElement(cv.MORPH_RECT, (1, 5), (-1, -1))
binary = cv.morphologyEx(binary, cv.MORPH_DILATE, se)
out, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
x, y, w, h = cv.boundingRect(contours[c])
area = cv.contourArea(contours[c])
if area < 200:
continue
if h > (3*w) or h < 20:
continue
cv.rectangle(src, (x, y), (x+w, y+h), (0, 0, 255), 1, 8, 0)

cv.imshow("result", src)
cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github