首页 > 编程学习 > OpenCV:图像处理常见的两种噪声

OpenCV:图像处理常见的两种噪声

发布时间:2022/5/14 15:43:14

椒盐噪声

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cstdlib>
#include <iostream>

using namespace cv;
using namespace std;

//图像添加椒盐噪声
Mat AddSaltNoise(const Mat srcImage,int n)
{
	Mat resultImage = srcImage.clone();
	for (int k = 0; k < n; k++)
	{
		//随机取值行列
		int i = rand() % resultImage.cols;
		int j = rand() % resultImage.rows;
		//图像通道判定
		if (resultImage.channels()==1)
		{
			resultImage.at<uchar>(j, i) = 255;
		}
		else
		{
			resultImage.at<Vec3b>(j, i)[0] = 255;
			resultImage.at<Vec3b>(j, i)[1] = 255;
			resultImage.at<Vec3b>(j, i)[2] = 255;
		}
	}
	return resultImage;
}

int main()
{
	Mat srcImage = imread("323195.jpg");
	resize(srcImage, srcImage,Size(320,240));
	if (srcImage.empty())
	{
		cout << "----------- 读取图片失败-----------";
		return -1;
	}
	Mat resultImage = AddSaltNoise(srcImage,5000);
	imshow("srcImage", srcImage);
	imshow("resultImage", resultImage);
	waitKey();
	return 0;
}

高斯噪声 

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <limits>

using namespace cv;
using namespace std;

double generateGaussianNoise(double mu,double sigma)
{
	//定义最小值
	const double epsilon = numeric_limits<double>::min();
	static double z0, z1;
	static bool flag = false;
	flag = !flag;
	//flag为假构造高斯随机变量X
	if (!flag)
	{
		return z1*sigma + mu;
	}
	double u1, u2;
	//构造随机变量
	do
	{
		u1 = rand()*(1.0/RAND_MAX);
		u2 = rand()*(1.0 / RAND_MAX);
	} while (u1<=epsilon);
	//flag为真构造高斯随机变量X
	z0 = sqrt(-2.0*log(u1))*cos(2*CV_PI*u2);
	z1 = sqrt(-2.0*log(u1))*sin(2*CV_PI*u2);
	return z0*sigma + mu;
}

//为图像添加高斯噪声
Mat AddGaussianNoise(Mat& srcImage)
{
	Mat resultImage = srcImage.clone();
	int channels = resultImage.channels();
	int nRows = resultImage.rows;
	int nCols = resultImage.cols*channels;
	//判断图像的连续性
	if (resultImage.isContinuous())
	{
		nCols *= nRows;
		nRows = 1;
	}
	for (int i = 0; i < nRows; ++i)
	{
		for (int j = 0; j < nCols; ++j)
		{
			//添加高斯噪声
			int val = resultImage.ptr<uchar>(i)[j] + generateGaussianNoise(2, 0.8) * 32;
			if (val<0)
			{
				val = 0;
			}
			if (val>255)
			{
				val = 255;
			}
			resultImage.ptr<uchar>(i)[j] = (uchar)val;
		}
	}
	return resultImage;
}

int main()
{
	Mat srcImage = imread("323195.jpg");
	if (!srcImage.data)
	{
		cout << "---------- 读取图片失败 ------------"<<endl;
		return -1;
	}
	resize(srcImage, srcImage,Size(320,240));
	imshow("srcImage",srcImage);
	Mat resultImage = AddGaussianNoise(srcImage);
	imshow("resultImage", resultImage);
	waitKey();
	return 0;
}

Copyright © 2010-2022 ngui.cc 版权所有 |关于我们| 联系方式| 豫B2-20100000