Opencv高斯噪聲生成與處理
阿新 • • 發佈:2018-12-20
測試環境:vs2012+opencv2.4.10
#include <stdio.h> #include <opencv2/core/core.hpp> #include <opencv2/core/core.hpp>//cv::Mat是一個n維矩陣類 #include <opencv2/highgui/highgui.hpp>//提供輸入輸出介面 #include <opencv2/imgproc/imgproc.hpp>//影象處理 #include "iostream" using namespace cv; using namespace std; //mu高斯函式的偏移,sigma高斯函式的標準差 double generateGaussianNoise(double mu, double sigma) { //定義小值,numeric_limits<double>::min()是函式,返回編譯器允許的double型數最小值 const double epsilon = std::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(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<uchar>(i)[j] + generateGaussianNoise(2, 0.8) * 32; if (val < 0) val = 0; if (val > 255) val = 255; result.ptr<uchar>(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; }
測試圖片: