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

本文关键字:像素 灰度 输出 Emgu CV 访问 使用 | 更新日期: 2023-09-27 18:37:28

我正在尝试将灰度图像中每个像素的值保存到文本文件中。例如,如果像素位置 (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 处放置一个断点,程序似乎在到达断点之前冻结了。我真的不知道我的方法有什么问题。任何想法将不胜感激,我很乐意根据要求提供更多信息。提前谢谢!

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

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

希望有帮助。