(原創) 如何對圖片加入Salt and Pepper Noise? (.NET) (C/C++) (C++/CLI) (GDI+) (Image Processing)
Salt and Pepper的公式如下
I(nim, i, j) = 0 if uniform(0, 1) < salt
I(nim, i, j) = 255 if uniform(0, 1) > 1 - pepper
I(nim, i, j) = I(im, i, j) otherwise
uniform(0, 1) : ramdom variable uniformly distributed over[0, 1]
I(nim, i, j) = 255 if uniform(0, 1) > 1 - pepper
I(nim, i, j) = I(im, i, j) otherwise
uniform(0, 1) : ramdom variable uniformly distributed over[0, 1]
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : SaltAndPepperNoise.cpp
5Compiler : Visual C++ 8.0 / C++/CLI
6Description : Demo how to process Salt and Pepper Noise
7Release : 12/20/2006 1.0
8*/
9
10#include "stdafx.h"
11#include "stdlib.h"
12
13using namespace System::Drawing;
14using namespace System::Drawing::Imaging;
15
16void saltpepperNoise(Bitmap^, Bitmap^, double&, double&);
17
18int main() {
19 // Read lena.jpg
20 Bitmap^ oriImg = gcnew Bitmap("lena.jpg");
21 // Declare Gaussian image for lena.jpg
22 Bitmap^ spImg = gcnew Bitmap(oriImg->Width, oriImg->Height);
23
24 // Salt-and-Pepper noise with salt rate=5% and pepper rate=5%
25 double salt = 0.05, pepper = 0.05;
26 saltpepperNoise(oriImg, spImg, salt, pepper);
27 spImg->Save("lena_saltpepper.jpg");
28
29 return 0;
30
31}
32
33void saltpepperNoise(Bitmap^ oriImg, Bitmap^ spImg, double& salt, double& pepper) {
34 for(int y = 0; y != oriImg->Height; ++y) {
35 for(int x = 0; x != oriImg->Width; ++x) {
36 double val = (double)rand() / RAND_MAX;
37
38 if (val < salt) {
39 spImg->SetPixel(x, y, Color::Black);
40 }
41 else if (val > 1-pepper) {
42 spImg->SetPixel(x, y, Color::White);
43 }
44 else {
45 spImg->SetPixel(x, y, oriImg->GetPixel(x, y));
46 }
47 }
48 }
49}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : SaltAndPepperNoise.cpp
5Compiler : Visual C++ 8.0 / C++/CLI
6Description : Demo how to process Salt and Pepper Noise
7Release : 12/20/2006 1.0
8*/
9
10#include "stdafx.h"
11#include "stdlib.h"
12
13using namespace System::Drawing;
14using namespace System::Drawing::Imaging;
15
16void saltpepperNoise(Bitmap^, Bitmap^, double&, double&);
17
18int main() {
19 // Read lena.jpg
20 Bitmap^ oriImg = gcnew Bitmap("lena.jpg");
21 // Declare Gaussian image for lena.jpg
22 Bitmap^ spImg = gcnew Bitmap(oriImg->Width, oriImg->Height);
23
24 // Salt-and-Pepper noise with salt rate=5% and pepper rate=5%
25 double salt = 0.05, pepper = 0.05;
26 saltpepperNoise(oriImg, spImg, salt, pepper);
27 spImg->Save("lena_saltpepper.jpg");
28
29 return 0;
30
31}
32
33void saltpepperNoise(Bitmap^ oriImg, Bitmap^ spImg, double& salt, double& pepper) {
34 for(int y = 0; y != oriImg->Height; ++y) {
35 for(int x = 0; x != oriImg->Width; ++x) {
36 double val = (double)rand() / RAND_MAX;
37
38 if (val < salt) {
39 spImg->SetPixel(x, y, Color::Black);
40 }
41 else if (val > 1-pepper) {
42 spImg->SetPixel(x, y, Color::White);
43 }
44 else {
45 spImg->SetPixel(x, y, oriImg->GetPixel(x, y));
46 }
47 }
48 }
49}
原圖
執行結果