(原創) 如何對有Noise圖片做Box Filter? (.NET) (C/C++) (C++/CLI) (GDI+) (Image Processing)
1
/*
2
(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4
Filename : BoxFilter.cpp
5
Compiler : Visual C++ 8.0 / C++/CLI
6
Description : Demo how to use BoxFilter
7
Release : 12/20/2006 1.0
8
*/
9
#include "stdafx.h"
10
#include <iostream>
11
12
using namespace System::Drawing;
13
using namespace System::Drawing::Imaging;
14
using namespace std;
15
16
void boxFilter(Bitmap^, Bitmap^, int, int);
17
int colorToInt(Color);
18
19
int main() {
20
// Read Gaussian noise image for lena.jpg
21
Bitmap^ gauImg = gcnew Bitmap("lena_gaussian.jpg");
22
// Declare Box Filter image for lena.jpg
23
Bitmap^ bfImg = gcnew Bitmap(gauImg->Width, gauImg->Height);
24
boxFilter(gauImg, bfImg, 3, 3);
25
bfImg->Save("lena_gaussian_boxfilter3x3.jpg");
26
27
return 0;
28
}
29
30
void boxFilter(Bitmap^ oriImg, Bitmap^ bfImg, int filterW, int filterH) {
31
int adjustX = (filterW % 2) ? 1 : 0;
32
int adjustY = (filterH % 2) ? 1 : 0;
33
int xBound = (int)(filterW/2);
34
int yBound = (int)(filterH/2);
35
36
for (int y = 0; y != oriImg->Height; ++y) {
37
for (int x = 0; x != oriImg->Width; ++x) {
38
int sum = 0, cnt = 0;
39
for (int v = -yBound; v != yBound + adjustY; ++v) {
40
for (int u = -xBound; u != xBound + adjustX; ++u) {
41
// check boundary
42
if (x + u < 0 || y + v < 0 || x + u >= oriImg->Width || y+v >= oriImg->Height)
43
continue;
44
45
sum += colorToInt(oriImg->GetPixel(x + u, y + v));
46
++cnt;
47
}
48
}
49
50
double val = (double)sum / cnt;
51
bfImg->SetPixel(x, y, Color::FromArgb(val,val,val));
52
}
53
}
54
}
55
56
// Convert RGB to gray level int
57
int colorToInt(Color color) {
58
return (color.R + color.G + color.B) / 3;
59
}

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

50

51

52

53

54

55

56

57

58

59

原圖

執行結果
