(原創) 如何對圖片加入Salt and Pepper Noise? (.NET) (C/C++) (C++/CLI) (GDI+) (Image Processing)
Salt and Pepper的公式如下





1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : SaltAndPepperNoise.cpp
5
Compiler : Visual C++ 8.0 / C++/CLI
6
Description : Demo how to process Salt and Pepper Noise
7
Release : 12/20/2006 1.0
8
*/
9
10
#include "stdafx.h"
11
#include "stdlib.h"
12
13
using namespace System::Drawing;
14
using namespace System::Drawing::Imaging;
15
16
void saltpepperNoise(Bitmap^, Bitmap^, double&, double&);
17
18
int 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
33
void 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

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

原圖

執行結果
