#include <cv.h> #include <highgui.h> //图像视频输出/输入头文件 using namespace std; IplImage* AddGuassianNoise(IplImage* src) //添加高斯噪声 { IplImage* dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); IplImage* noise = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); CvRNG rng = cvRNG(-1); cvRandArr(&rng, noise, CV_RAND_NORMAL, cvScalarAll(0), cvScalarAll(15)); cvAdd(src, noise, dst); return dst; } IplImage* AddPepperNoise(IplImage* src) //添加胡椒噪声,随机黑色点 { IplImage* dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); cvCopy(src, dst); for (int k = 0; k<8000; k++) { int i = rand() % src->height; int j = rand() % src->width; CvScalar s = cvGet2D(src, i, j); if (src->nChannels == 1) { s.val[0] = 0; } else if (src->nChannels == 3) { s.val[0] = 0; s.val[1] = 0; s.val[2] = 0; } cvSet2D(dst, i, j, s); } return dst; } IplImage* AddSaltNoise(IplImage* src) //添加盐噪声,随机白色点 { IplImage* dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); cvCopy(src, dst); for (int k = 0; k<8000; k++) { int i = rand() % src->height; int j = rand() % src->width; CvScalar s = cvGet2D(src, i, j); if (src->nChannels == 1) { s.val[0] = 255; } else if (src->nChannels == 3) { s.val[0] = 255; s.val[1] = 255; s.val[2] = 255; } cvSet2D(dst, i, j, s); } return dst; } IplImage* AddPepperSaltNoise(IplImage* src) //添加椒盐噪声,随机黑白点 { IplImage* dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); cvCopy(src, dst); for (int k = 0; k<8000; k++) { int i = rand() % src->height; int j = rand() % src->width; int m = rand() % 2; CvScalar s = cvGet2D(src, i, j); if (src->nChannels == 1) { if (m == 0) { s.val[0] = 255; } else { s.val[0] = 0; } } else if (src->nChannels == 3) { if (m == 0) { s.val[0] = 255; s.val[1] = 255; s.val[2] = 255; } else { s.val[0] = 0; s.val[1] = 0; s.val[2] = 0; } } cvSet2D(dst, i, j, s); } return dst; } //算术均值滤波器——模板大小5*5 IplImage* ArithmeticMeanFilter(IplImage* src) { IplImage* dst = cvCreateImage(cvGetSize(src), src->depth, src->nChannels); cvSmooth(src, dst, CV_BLUR, 5); return dst; } int main() { IplImage * test, *test_1, *test_2; test = cvLoadImage("6013202130.jpg",0);//图片路径是 ConsoleApplication4 文件夹里,同时实验要求转为灰度图片 test_1 = cvCreateImage(cvSize((test->width), (test->height)), IPL_DEPTH_8U, 1); //创建图像,给指针赋值 test_2 = cvCreateImage(cvSize((test->width), (test->height)), IPL_DEPTH_8U, 1); //创建图像,给指针赋值 test_2 = AddGuassianNoise(test); test_1 = ArithmeticMeanFilter(test_2); cvNamedWindow("原图", CV_WINDOW_AUTOSIZE); cvShowImage("原图", test); cvNamedWindow("滤波后", CV_WINDOW_AUTOSIZE); cvShowImage("滤波后", test_1); cvNamedWindow("噪声后", CV_WINDOW_AUTOSIZE); cvShowImage("噪声后", test_2); cvWaitKey(0);//等待按键 cvDestroyWindow("zhang_fei_1"); cvDestroyWindow("zhang_fei_2"); cvDestroyWindow("zhang_fei_3"); cvReleaseImage(&test);//释放内存。 cvReleaseImage(&test_1); cvReleaseImage(&test_2); return 0; }