opencv学习-去除干扰线

操作步骤:

1.读取彩色图像,imread()

2.转换为灰度图像,cvtColor(src,dst,CV_BGR2GRAY)

3.转换为二值图像,adaptiveThreshold()

4,定义结构元素,getStructuringElement

5,形态学操作

代码如下:

#include
#include
using namespace std;
using namespace cv;

int main(){
	Mat src, gray_src,bin_src,dst;
	src = imread("./test4.png");
	if (src.empty()){
		cout << "input data error..." << endl;
		return -1;
	}
	namedWindow("input_image", WINDOW_NORMAL);
	imshow("input_image", src);

	cvtColor(src, gray_src, CV_BGR2GRAY);
	imshow("gray_image", gray_src);

	adaptiveThreshold(gray_src, bin_src, 255, ADAPTIVE_THRESH_MEAN_C,  THRESH_BINARY, 15, 2);
	imshow("binary_image", bin_src);
	
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));

	Mat temp;
	erode(bin_src, temp, kernel);
	dilate(temp, dst, kernel);
	//morphologyEx(bin_src, dst, CV_MOP_OPEN, kernel, Point(-1, -1));
	imshow("final", dst);
	waitKey(0);
	return 0;
}

效果图:

opencv学习-去除干扰线_第1张图片

为什么会去除不掉呢,因为开操作是除掉黑色背景中的白色小块,那么解决该问题就有两种方法:

1.用bitwise_not()将得到的二值图像反色,变成黑为背景白为前景。

2.将开操作变为闭操作。

代码分别为:

#include
#include
using namespace std;
using namespace cv;

int main(){
	Mat src, gray_src,bin_src,dst;
	src = imread("./test4.png");
	if (src.empty()){
		cout << "input data error..." << endl;
		return -1;
	}
	namedWindow("input_image", WINDOW_NORMAL);
	imshow("input_image", src);

	cvtColor(src, gray_src, CV_BGR2GRAY);
	imshow("gray_image", gray_src);

	adaptiveThreshold(gray_src, bin_src, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 2);
	bitwise_not(bin_src, bin_src);
	imshow("binary_image", bin_src);
	
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));

	Mat temp;
	erode(bin_src, temp, kernel);
	dilate(temp, dst, kernel);
	//morphologyEx(bin_src, dst, CV_MOP_OPEN, kernel, Point(-1, -1));
	imshow("final", dst);
	waitKey(0);
	return 0;
}

 

效果图:

opencv学习-去除干扰线_第2张图片

闭操作代码 :

#include
#include
using namespace std;
using namespace cv;

int main(){
	Mat src, gray_src,bin_src,dst;
	src = imread("./test4.png");
	if (src.empty()){
		cout << "input data error..." << endl;
		return -1;
	}
	namedWindow("input_image", WINDOW_NORMAL);
	imshow("input_image", src);

	cvtColor(src, gray_src, CV_BGR2GRAY);
	imshow("gray_image", gray_src);

	adaptiveThreshold(gray_src, bin_src, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 2);
	/*bitwise_not(bin_src, bin_src);*/
	imshow("binary_image", bin_src);
	
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));

	Mat temp;
	dilate(bin_src, temp, kernel);
	erode(temp, dst, kernel);
	//morphologyEx(bin_src, dst, CV_MOP_OPEN, kernel, Point(-1, -1));
	imshow("final", dst);
	waitKey(0);
	return 0;
}

效果图:

opencv学习-去除干扰线_第3张图片

 

 

你可能感兴趣的:(OpenCV)