1: public static Bitmap KuwaharaBlur(Bitmap Image, int Size)
2: {
3: System.Drawing.Bitmap TempBitmap = Image;
4: System.Drawing.Bitmap NewBitmap = new System.Drawing.Bitmap(TempBitmap.Width, TempBitmap.Height);
5: System.Drawing.Graphics NewGraphics = System.Drawing.Graphics.FromImage(NewBitmap);
6: NewGraphics.DrawImage(TempBitmap, new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), new System.Drawing.Rectangle(0, 0, TempBitmap.Width, TempBitmap.Height), System.Drawing.GraphicsUnit.Pixel);
7: NewGraphics.Dispose();
8: Random TempRandom = new Random();
9: int[] ApetureMinX = { -(Size / 2), 0, -(Size / 2), 0 };
10: int[] ApetureMaxX = { 0, (Size / 2), 0, (Size / 2) };
11: int[] ApetureMinY = { -(Size / 2), -(Size / 2), 0, 0 };
12: int[] ApetureMaxY = { 0, 0, (Size / 2), (Size / 2) };
13: for (int x = 0; x < NewBitmap.Width; ++x)
14: {
15: for (int y = 0; y < NewBitmap.Height; ++y)
16: {
17: int[] RValues = { 0, 0, 0, 0 };
18: int[] GValues = { 0, 0, 0, 0 };
19: int[] BValues = { 0, 0, 0, 0 };
20: int[] NumPixels = { 0, 0, 0, 0 };
21: int[] MaxRValue = { 0, 0, 0, 0 };
22: int[] MaxGValue = { 0, 0, 0, 0 };
23: int[] MaxBValue = { 0, 0, 0, 0 };
24: int[] MinRValue = { 255, 255, 255, 255 };
25: int[] MinGValue = { 255, 255, 255, 255 };
26: int[] MinBValue = { 255, 255, 255, 255 };
27: for (int i = 0; i < 4; ++i)
28: {
29: for (int x2 = ApetureMinX[i]; x2 < ApetureMaxX[i]; ++x2)
30: {
31: int TempX = x + x2;
32: if (TempX >= 0 && TempX < NewBitmap.Width)
33: {
34: for (int y2 = ApetureMinY[i]; y2 < ApetureMaxY[i]; ++y2)
35: {
36: int TempY = y + y2;
37: if (TempY >= 0 && TempY < NewBitmap.Height)
38: {
39: Color TempColor = TempBitmap.GetPixel(TempX, TempY);
40: RValues[i] += TempColor.R;
41: GValues[i] += TempColor.G;
42: BValues[i] += TempColor.B;
43: if (TempColor.R > MaxRValue[i])
44: {
45: MaxRValue[i] = TempColor.R;
46: }
47: else if (TempColor.R < MinRValue[i])
48: {
49: MinRValue[i] = TempColor.R;
50: }
51:
52: if (TempColor.G > MaxGValue[i])
53: {
54: MaxGValue[i] = TempColor.G;
55: }
56: else if (TempColor.G < MinGValue[i])
57: {
58: MinGValue[i] = TempColor.G;
59: }
60:
61: if (TempColor.B > MaxBValue[i])
62: {
63: MaxBValue[i] = TempColor.B;
64: }
65: else if (TempColor.B < MinBValue[i])
66: {
67: MinBValue[i] = TempColor.B;
68: }
69: ++NumPixels[i];
70: }
71: }
72: }
73: }
74: }
75: int j = 0;
76: int MinDifference = 10000;
77: for (int i = 0; i < 4; ++i)
78: {
79: int CurrentDifference = (MaxRValue[i] - MinRValue[i]) + (MaxGValue[i] - MinGValue[i]) + (MaxBValue[i] - MinBValue[i]);
80: if (CurrentDifference < MinDifference && NumPixels[i] > 0)
81: {
82: j = i;
83: MinDifference = CurrentDifference;
84: }
85: }
86:
87: Color MeanPixel = Color.FromArgb(RValues[j] / NumPixels[j],
88: GValues[j] / NumPixels[j],
89: BValues[j] / NumPixels[j]);
90: NewBitmap.SetPixel(x, y, MeanPixel);
91: }
92: }
93: return NewBitmap;
94: }