基于OpenCV的形态学处理
#include<iostream>
#include <opencv2/core.hpp>
#include<opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/video/tracking.hpp>
using namespace std;
using namespace cv;
void main()
{
Mat image;
image = cv::imread("page.jpg");
if (image.empty())
{
cout << "读取图像失败" << endl;
exit(EXIT_FAILURE);
}
cv::imshow("origional image", image);
cv::Mat gray;
cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
cv::imshow("原灰度图", gray);
cv::Mat result;
cv::morphologyEx(gray, result,
cv::MORPH_GRADIENT, cv::Mat());
cv::imshow("梯度图像", result);
cv::Mat dilated;
cv::dilate(image, dilated, cv::Mat());
int threshold = 80;
cv::threshold((dilated - image), result,
threshold, 255, cv::THRESH_BINARY);
cv::imshow("(膨胀后的图像 - 原始图像)*阈值化", result);
cv::Mat eroded;
cv::erode(image, eroded, cv::Mat());
threshold = 80;
cv::threshold((image - eroded), result,
threshold, 255, cv::THRESH_BINARY);
cv::imshow("(原始图像 - 腐蚀后的图像)*阈值化", result);
threshold = 70;
cv::threshold(gray, result,
threshold, 255, cv::THRESH_BINARY);
cv::imshow("阈值法提取文本内容", result);
cv::Mat element7(7, 7, CV_8U, cv::Scalar(1));
cv::morphologyEx(gray, result,
cv::MORPH_BLACKHAT, element7);
cv::imshow("7×7黑帽变换结果", result);
int c = waitKey(0);
if (c == 27)
{
exit;
}
destroyAllWindows();
}