c# - 使用Emgu CV访问和输出每个像素的灰度

标签 c# visual-studio-2010 opencv emgucv

我正在尝试将灰度图像中每个像素的值保存到文本文件中。例如,如果像素位置(x,y)的值为255(纯白色),则255将被保存在文本文件的相应坐标中。

这是我的代码。这是x86机器上Emgu CV 2.4.0,MSFT Visual Studio 2010和MSFT .NET 4.0中的WinForm应用程序。

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 = 0和j = MyImageGray.Width-1之后卡住了。它应该去处理下一行,但是整个Visual Studio 2010和应用程序都冻结了。冻结表示我的应用程序的窗口不能移动,VS中的光标也不能移动。我必须通过按Shift + F5取消该应用程序。同时,当我读取(0,414)像素时,出现“在Emgu.CV.dll中发生'Emgu.CV.Util.CvException类型的第一次机会异常”。实际上,调试消息如下所示:
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 = MyImageGray.Width-1处设置一个断点,并且程序在到达断点之前似乎已冻结。
我真的不知道我的方法有什么问题。任何想法将不胜感激,我很乐意根据要求提供更多信息。谢谢你!

最佳答案

以这种方式访问​​像素值时,应使用pixel = MyImageGray[i, j];而不是pixel = MyImageGray[j, i];。第一个索引是行,第二个索引是列。

希望能有所帮助。

关于c# - 使用Emgu CV访问和输出每个像素的灰度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11081467/

相关文章:

c++ - 无法从 dll、vs2010、c++ 导出类

.net - 如何使用转储文件来诊断内存泄漏?

python - 如何使用 opencv python 调整亮度、对比度和振动度?

opencv - 图像计算方差背后的理论是什么?

c# - EWS : How to update IsRead property of an EmailMessage

javascript - 数据到达 Controller 但不查看

c# - StructureMap 和嵌套泛型

c# - Xamarin CollectionView 与 Horizo​​ntalItemSpacing 相等的项目宽度

visual-studio-2008 - 使用Visual Studio 2008和2010进行一个ASP.NET-MVC-2项目?

python - 如何使用 OpenCV 从建筑物的图片中计算 window 的尺寸?