灰度化 -> 二值化 -> 建立满足不同需求的结构元素 -> 开运算
若要去除垂直线,则建立水平长条状矩形结构元素
若要去除水平线,则建立垂直长条状矩形结构元素
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat src1, src2, gray_src, dst;
src1 = imread("/Users/apple/Desktop/chars.png", IMREAD_COLOR);
//src2 = imread("/Users/apple/Desktop/test2.jpg", IMREAD_COLOR);
if (src1.empty()) { // if (!src.data())
cout << "could not load image..." << endl;
return -1;
}
imshow("input", src1);
cvtColor(src1, gray_src, CV_BGR2GRAY);
imshow("output_gray", gray_src);
Mat binImg;
adaptiveThreshold(~gray_src, binImg, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 25, -2);
Mat kernel = getStructuringElement(MORPH_RECT, Size(4, 4), Point(-1, -1));
//morphologyEx(binImg, binImg, MORPH_OPEN, kernel);
imshow("output binary image", binImg);
// 水平结构元素
Mat hline = getStructuringElement(MORPH_RECT, Size(src1.cols / 16, 1), Point(-1, -1));
// 垂直结构元素
Mat vline = getStructuringElement(MORPH_RECT, Size(1, src1.rows / 16), Point(-1, -1));
Mat temp;
erode(binImg, temp, kernel);
dilate(temp, dst, kernel);
imshow("temp", temp);
imshow("output", ~dst);
waitKey(0);
return 0;
}