本文共 2008 字,大约阅读时间需要 6 分钟。
测试环境:vs2012+opencv2.4.10
#include#include #include //cv::Mat是一个n维矩阵类#include //提供输入输出接口#include //图像处理#include "iostream"using namespace cv;using namespace std;//mu高斯函数的偏移,sigma高斯函数的标准差double generateGaussianNoise(double mu, double sigma){ //定义小值,numeric_limits ::min()是函数,返回编译器允许的double型数最小值 const double epsilon = std::numeric_limits ::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(cv::Mat &image){ cv::Mat result = image.clone(); int channels = image.channels(); int rows = image.rows, cols = image.cols * image.channels(); //判断图像连续性 if (result.isContinuous()) cols = rows * cols, rows = 1; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { //添加高斯噪声 int val = result.ptr (i)[j] + generateGaussianNoise(2, 0.8) * 32; if (val < 0) val = 0; if (val > 255) val = 255; result.ptr (i)[j] = (uchar)val; } } return result;}int main(){ Mat src=imread("lena512color.jpg"); Mat img = src.clone(); Mat img1 = src.clone(); imshow("原图",src); Mat sobelx; Sobel(src, sobelx, CV_32F, 1, 0); imshow("Sobel的结果",sobelx); Mat dst=addGaussianNoise(src); //加入高斯噪声 imshow("高斯噪声图像",dst); medianBlur(src,dst,3); //中值滤波,3*3模板内排序并求中值取代原像素 imshow("中值滤波结果",dst); Mat dst1=addGaussianNoise(src); //加入高斯噪声 blur(img,dst1,Size(3,3));//均值滤波,3*3模板内求取中间值取代原像素 imshow("均值滤波结果",dst1); Mat dst2=addGaussianNoise(src); //加入高斯噪声 GaussianBlur( img1, dst2, Size( 3, 3 ), 0, 0 );//高斯滤波, imshow("高斯滤波结果",dst2); Rect r( 0, 0, 100, 100); //img = Scalar(50);//将图像img的像素赋值为50 Mat smallImg = img(r);//截取显示img图像中形状为r的部分图像 imshow("截图显示结果",smallImg); waitKey(NULL);//无限等待 return EXIT_SUCCESS;}
测试图片:
转载地址:http://hbqen.baihongyu.com/