title: Accessing and output the gray scale of each pixel using Emgu CV
body: <p>I'm trying to save the value of each pixel in a gray scale image into a text file. For example, if a pixel location (x, y) has a value of 255 (pure white), an 255 will be saved in the correspondent coordinate in a text file. </p>
  
  <p>Here's my code. It's a WinForm applicaton in Emgu CV 2.4.0, MSFT Visual Studio 2010 and MSFT .NET 4.0 on an x86 machine.</p>
  
  <pre><code>OpenFileDialog OpenFile = new OpenFileDialog();//open an image file.
          if (OpenFile.ShowDialog() == DialogResult.OK)
          {
              Image&lt;Bgr, Byte&gt; My_Image = new Image&lt;Bgr, byte&gt;(OpenFile.FileName);//Read the file as an Emgu.CV.Structure.Image object.
              Image&lt;Gray, Byte&gt; MyImageGray = new Image&lt;Gray, Byte&gt;(My_Image.Width, My_Image.Height);//Initiate an Image object to receive the gray scaled image. 
              CvInvoke.cvCvtColor(My_Image.Ptr, MyImageGray.Ptr, COLOR_CONVERSION.CV_RGB2GRAY);//convert the BGR image to gray scale and save it in MyImageGray
              CvInvoke.cvNamedWindow("Gray");
              CvInvoke.cvShowImage("Gray", MyImageGray.Ptr);
              StreamWriter writer = File.CreateText("test.txt");//Initiate the text file writer
              Gray pixel;
              //try to iterate through all the image pixels.
              for (int i = 0; i &lt; MyImageGray.Height; i++)
              {
                  for (int j = 0; j &lt; MyImageGray.Width; j++)
                  {
                      pixel = MyImageGray[j, i];
                      Console.WriteLine(string.Format("Writing column {0}", j));//debug output
                      writer.Write(string.Format("{0} ",pixel.Intensity));
                  }
                  writer.WriteLine();
              }
          }
  </code></pre>
  
  <p>I tried to run it but for some reason, it got stuck after i=0 and j=MyImageGray.Width-1. It should go to process the next row but the whole Visual Studio 2010 and the application froze. By froze I mean the window of my application can not be moved and the cursor in the VS can not move either. I have to kill the application by pressing Shift+F5. Meanwhile, I got a "A first chance exception of type 'Emgu.CV.Util.CvException' occurred in Emgu.CV.dll" when I'm reading the (0, 414) pixel. Actually the debug message looks like: </p>
  
  <pre><code>Writing column 413
  WritinA first chance exception of type 'Emgu.CV.Util.CvException' occurred in     Emgu.CV.dll
  g column 414
  Writing column 415
  </code></pre>
  
  <p>I tried to put a break point at i=MyImageGray.Width-1 and the program seems to freeze before it hit the break point.
  I really don't know what's wrong in my approach. Any idea would be appreciated and I'm happy to provide more info upon request. Thanks ahead!</p>