图像处理——去除图像上杂乱的干扰

源码

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <iostream>

using namespace cv;
using namespace std;

//定义全局变量存储路径信息
char filename[] = { 0 };

int main(int argc, char** argv)
{  
	Mat src, dest, gray, binary;
	cout << "----------------------------------------------------------------" << endl << endl;
	cout << "Please enter a image path as follows and press Enter." << endl << endl;
	cout << "Eg: F:/cvpicture/flower.png" << endl << endl;
	cout << "ps: Image preview will automatically turn off after 30 seconds!" << endl << endl;
	cout << "----------------------------------------------------------------" << endl;
	cout << "Please enter the path:";
	cin >> filename;
	//调用imread()函数读取图像
	src = imread(filename);

	//判断是否读取成功
	while (!src.data)
	{
		cout << "The path of image is error,and could not load image..." << endl;
		cout << "Please enter the path:";
		cin >> filename;
		src = imread(filename);
	}
	namedWindow("input image", 1);//创建窗口以显示读取的图像
	imshow("input image", src);//显示图像

	//判断原图像的通道数,如果的是三通道图像则将图像转化为单通道灰度图像
	if (3 == src.channels())
	{
		cvtColor(src, gray, CV_BGR2GRAY);
	}
	else
	{
		gray = src;
	}
	//将灰度图像二值化
	adaptiveThreshold(~gray, binary, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, -1);

	//定义一个掩模
	Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
	morphologyEx(binary, dest, CV_MOP_OPEN, kernel);//调用形态学操作函数
	bitwise_not(dest, dest);//反转背景颜色
	namedWindow("dest image", 1);//创建目标图像显示窗口
	imshow("dest image", dest);
	waitKey(3000);//显示窗口停留时间30s
	cvDestroyWindow("dest image");//释放显示窗口
	cvDestroyWindow("input image");
	
	cout << "--------------------------------------------------------" << endl << endl;
	cout << "Tips:Do you want to save the processed image?" << endl << endl;
	cout << "Save press:y    Don't save press:n" << endl << endl;
	cout << "--------------------------------------------------------" << endl;
	cout << "Please enter:";
	//定义字符型变量存储用户输入信息
	char c;
	cin >> c;
	while (c != 'y' && c != 'n')
	{
		cout << endl;
		cout << "Sorry,input is error,please re-enter:" << endl;
		cin >> c;
		cout << endl;
	}
	if (c== 'y')
	{
		cout << "Please enter the saved path:";
		cin >> filename;
		imwrite(filename, dest);
		cout << endl;
		cout << "Image saved successfully!" << endl;
	}
	else if (c == 'n')
	{
		cout << endl;
		cout << "Unsaved!" << endl;
		return 0;
	}
	return 0;
}


版权声明:本文为JonNoah原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。