(原創) 如何對圖片加入Gaussian Noise? (.NET) (C/C++) (C++/CLI) (GDI+) (Image Processing)

 1/* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : GaussianNoise.cpp
 5Compiler    : Visual C++ 8.0 / C++/CLI
 6Description : Demo how to process Gaussian Noise
 7Release     : 12/19/2006 1.0
 8*/

 9
10#include "stdafx.h"
11#include "stdlib.h"
12
13using namespace System::Drawing;
14using namespace System::Drawing::Imaging;
15// Normal random number generator
16double normal();
17// Convert RGB to gray level int
18int colorToInt(Color color);
19// Process Gaussian noise
20void gaussianNoise(Bitmap^, Bitmap^int&);
21
22int main() {
23  // Read lena.jpg
24  Bitmap^ oriImg = gcnew Bitmap("lena.jpg");
25  // Declare Gaussian image for lena.jpg
26  Bitmap^ gauImg = gcnew Bitmap(oriImg->Width, oriImg->Height);
27
28  // Gaussian Filter with amplitude 10
29  int amp = 10;
30  gaussianNoise(oriImg, gauImg, amp);
31  gauImg->Save("lena_gaussian.jpg");
32
33  return 0;
34}

35
36// Process Gaussian noise
37void gaussianNoise(Bitmap^ oriImg, Bitmap^ resImg, int& amp) {
38  const int WHITE = 255;
39  const int BLACK = 0;
40
41  for (int y = 0; y < oriImg->Height; ++y) {
42    for (int x = 0; x < oriImg->Width; ++x) {
43      double random = normal();
44      int noise = (int)(amp * random);
45      int newVal = colorToInt(oriImg->GetPixel(x, y)) + noise;
46
47      if (newVal > WHITE)
48        resImg->SetPixel(x, y, Color::White);
49      else if (newVal < BLACK)
50        resImg->SetPixel(x, y, Color::Black);
51      else
52        resImg->SetPixel(x, y, Color::FromArgb(newVal, newVal, newVal));
53    }

54  }

55}

56
57// Normal random number generator
58double normal() {
59  double val = 0;
60
61  for(int i = 0; i != 12++i)
62    val += ((double)rand() / RAND_MAX);
63
64  return val - 6.0;
65}

66
67// Convert RGB to gray level int
68int colorToInt(Color color) {
69  return (color.R + color.G + color.B) / 3;
70}


原圖


執行結果

posted on 2006-12-19 21:46  真 OO无双  阅读(6152)  评论(1编辑  收藏  举报

导航