像下面这样使用 Emgu OpenCV for .NET 的东西会起作用。
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System;
using System.Drawing;
using System.IO;
using (Image<Bgr, Byte> img = new Image<Bgr, Byte>("MyImage.jpg"))
{
Matrix<Int32> matrix = new Matrix<Int32>(img.Width, img.Height);
for (int i = 0; i<img.Height;i++)
{
for (int j = 0; j<img.Width;j++)
{
if (img.Data[i,j,2] == 255 &&
img.Data[i,j,1] == 255 &&
img.Data[i,j,0] == 255)
{
matrix.Data[i,j] = 0;
}
else
{
matrix.Data[i,j] = 1;
}
}
}
TextWriter tw = new StreamWriter("output.txt");
for (int i = 0; i<img.Height;i++)
{
for (int j = 0; j<img.Width;j++)
{
tw.Write(matrix.Data[i,j]);
}
tw.Write(tw.NewLine);
}
}
请注意,上面的代码片段加载彩色图像并创建一个白色为 0 和 1 的矩阵,否则。
为了加载和处理灰度图像,它Image<Bgr, Byte>
变成了一个Image<Gray, Byte>
,并且比较简化为
if (img.Data[i,j,0] == 255)
。
还要进行阈值处理(从彩色到灰度到黑白的转换),您可以使用 Otsu 的阈值处理cvThreshold
方法,使用类似的方法:
int threshold = 150;
Image<Bgr, Byte> img = new Image<Bgr, Byte>("MyImage.jpg");
Image<Gray, Single> img2 = img1.Convert<Gray, Single>();
Image<Gray, Single> img3 = new Image<Gray, Single>(img2.Width, img2.Height);
CvInvoke.cvThreshold(img2, img3, threshold, 255, THRESH.CV_THRESH_OTSU);
其他可能的工具包括
convert
来自 ImageMagick 和pnmoraw
netpbm,如您链接的 URL 中所述,带有示例片段 convert lib/dragon_face.xbm pbm: | pnmnoraw
。
- 使用PIL(Python 图像库)迭代图像数据和 Python IO 函数来写入输出数据
- 使用System.Drawing.Bitmap具体使用 GetPixel 方法来遍历图像数据,并使用 C# IO 函数写入输出数据。