图像添加高斯噪声、胡椒噪声、盐噪声和椒盐噪声

1、盐椒噪声

图像加入椒盐噪声开始,椒盐噪声其实就是使图像的一些随机的像素为黑色(0)或者白色(255):
盐噪声又称白噪声,在图像中添加一些随机的白色像素点(255);胡椒噪声是在图像中添加一些随机的黑色像素点(0);盐椒噪声是在图像中既有白色像素点,又有黑色像素点。

添加代码如下:

//盐噪声
void salt(Mat& image,int n)
{
    for(int k=0; k(j,i) = 255;
        }else{
	    image.at(j,i)[0] = 255;
            image.at(j,i)[1] = 255;
            image.at(j,i)[2] = 255;
        }
    }
}
//椒盐噪声
void peppersalt(Mat& image,int n)
{
    for(int k=0; k(j,i) = 255;
        }else{
            image.at(j,i)[0] = 255;
            image.at(j,i)[1] = 255;
	    image.at(j,i)[2] = 255;
        }
    }
	for(int k=n/2;k(j,i) = 0;
        }else{
            image.at(j,i)[0] = 0;
            image.at(j,i)[1] = 0;
	    image.at(j,i)[2] = 0;
        }
	}
}
2、高斯噪声

Box-Muller变换:假设随机变量x1, x2来自独立的处于[0,1]之间的均匀分布,则经过下面两个式子产生的随机变量z1, z2服从标准高斯分布:



#include 
#include 
#include 

using namespace cv;
using namespace std;

#define TWO_PI 6.2831853071795864769252866
 
double generateGaussianNoise()
{
	static bool hasSpare = false;
	static double rand1, rand2;
 
	if(hasSpare)
	{
		hasSpare = false;
		return sqrt(rand1) * sin(rand2);
	}
 
	hasSpare = true;
 
	rand1 = rand() / ((double) RAND_MAX);
	if(rand1 < 1e-100) rand1 = 1e-100;
	rand1 = -2 * log(rand1);
	rand2 = (rand() / ((double) RAND_MAX)) * TWO_PI;
 
	return sqrt(rand1) * cos(rand2);
}


void AddGaussianNoise(Mat& I)
{

	CV_Assert(I.depth() != sizeof(uchar));
	int channels = I.channels();
	int nRows = I.rows;
	int nCols = I.cols * channels;

	if(I.isContinuous()){
		nCols *= nRows;
		nRows = 1;
	}

	int i,j;
	uchar* p;
	for(i = 0; i < nRows; ++i){
		p = I.ptr(i);
		for(j = 0; j < nCols; ++j){
			double val = p[j] + generateGaussianNoise() * 128;
			if(val < 0)
				val = 0;
			if(val > 255)
				val = 255;
			p[j] = (uchar)val;

		}
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
    Mat image;
    image = imread(argv[1], 1); // Read the file

    if(! image.data ) // Check for invalid input
    {
        cout << "Could not open or find the image" << std::endl ;
        return -1;
    }

	namedWindow( "高斯噪声", WINDOW_AUTOSIZE ); // Create a window for display.
        imshow( "高斯噪声", image ); // Show our image inside it.
	AddGaussianNoise(image);

	namedWindow( "高斯噪声", WINDOW_AUTOSIZE ); 
        imshow( "高斯噪声", image ); 
        waitKey(0); 
        return 0;
}


你可能感兴趣的:(图像处理,C++,openCV)