main.cpp
#include <istream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char **argv) {
Mat src, gray_dst, bin_dst, h_dst, v_dst, dst;
// 加载图片
src = imread("../../picture/chars.png", 1);
if (!src.data) {
printf("No image data \n");
return -1;
}
char src_title[] = "src";
namedWindow(src_title, WINDOW_AUTOSIZE);
imshow(src_title, src);
// 转换成灰度图像
char gray_title[] = "gray";
namedWindow(gray_title, WINDOW_AUTOSIZE);
cvtColor(src, gray_dst, COLOR_BGR2GRAY);
imshow(gray_title, gray_dst);
//转换成二值图像
char bin_title[] = "bin";
namedWindow(bin_title, WINDOW_AUTOSIZE);
adaptiveThreshold(~gray_dst, bin_dst, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -2);
imshow(bin_title, bin_dst);
// 提取水平直线
char h_title[] = "h";
Mat h = getStructuringElement(MORPH_RECT, Size(src.cols / 16, 1), Point(-1, -1));
Mat tmp1;
erode(bin_dst, tmp1, h);
dilate(tmp1, h_dst, h);
// 提取水平直线等价api
// morphologyEx(bin_dst, h_dst, MORPH_OPEN, h);
namedWindow(h_title, WINDOW_AUTOSIZE);
imshow(h_title, h_dst);
// 提取垂直直线
char v_title[] = "v";
Mat v = getStructuringElement(MORPH_RECT, Size(1, src.rows / 16), Point(-1, -1));
Mat tmp2;
erode(bin_dst, tmp2, v);
dilate(tmp2, v_dst, v);
// 提取垂直直线等价api
// morphologyEx(bin_dst, v_dst, MORPH_OPEN, v);
namedWindow(v_title, WINDOW_AUTOSIZE);
imshow(v_title, v_dst);
// 字符提取
char dst_title[] = "dst";
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
// Mat tmp3;
// erode(bin_dst, tmp3, kernel);
// dilate(tmp3, dst, kernel);
morphologyEx(bin_dst, dst, MORPH_OPEN, kernel);
bitwise_not(dst, dst);
blur(dst, dst, Size(3, 3), Point(-1, -1));
namedWindow(dst_title, WINDOW_AUTOSIZE);
imshow(dst_title, dst);
// 等待按键
waitKey(0);
return 0;
}