Search code examples
c#visual-studio-2010opencvemgucv

Accessing and output the gray scale of each pixel using Emgu CV


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.

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.

OpenFileDialog OpenFile = new OpenFileDialog();//open an image file.
        if (OpenFile.ShowDialog() == DialogResult.OK)
        {
            Image<Bgr, Byte> My_Image = new Image<Bgr, byte>(OpenFile.FileName);//Read the file as an Emgu.CV.Structure.Image object.
            Image<Gray, Byte> MyImageGray = new Image<Gray, Byte>(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 < MyImageGray.Height; i++)
            {
                for (int j = 0; j < 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();
            }
        }

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:

Writing column 413
WritinA first chance exception of type 'Emgu.CV.Util.CvException' occurred in     Emgu.CV.dll
g column 414
Writing column 415

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!


Solution

  • When you access pixel values that way you should use pixel = MyImageGray[i, j]; instead of pixel = MyImageGray[j, i];. First index is row and a second one is column.

    Hope that helps.