C#生成二进制蒙版,图像中没有灰度值/噪点?

时间:2018-10-01 19:08:21

标签: c# .net gdi+

在C#中,如何生成图像中没有灰度值/噪声的二进制掩码?

现在,我能够生成一个非常简单的输出,该输出看起来非常接近我想要的输出,但是在白色斑点的内部和外部的边缘周围都有噪点(您需要一直放大以查看噪音)。我打算稍后使用该图像进行图像处理,但是除了图像中的黑白值外,不能有其他任何东西。

图片: Crop 1 Crop 2

代码:

    public CropedImage(List<Node> nodes)
    {
        InitializeComponent();
        //List<PointF> listpoints = new List<PointF>();
        nodes.ToArray();
        PointF[] points = new PointF[nodes.Count];
        for(int i = 0; i < nodes.Count; ++i)
        {
            points[i].X = nodes[i].X;
            points[i].Y = nodes[i].Y;
        }

        Image SourceImage = ImageOperations.GetImage(MainForm.imageMatrix, pictureBox1);

        using (Graphics g = Graphics.FromImage(SourceImage))
        {
            Color black = ColorTranslator.FromHtml("#000000");
            Color white = ColorTranslator.FromHtml("#FFFFFF");


            using (Brush b = new SolidBrush(black))
            {
                Rectangle rect = new Rectangle();
                g.FillRectangle(b, 0, 0, MainForm.WIDTH, MainForm.HEIGHT);
            }
            using (Brush b2 = new SolidBrush(white))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.FillClosedCurve(b2, points, 0);
            }
        }

    }

2 个答案:

答案 0 :(得分:2)

如何更改

g.SmoothingMode = SmoothingMode.AntiAlias;

g.SmoothingMode = SmoothingMode.None;

如果我理解正确,那可以解决您的问题。

答案 1 :(得分:1)

正如eocron所说,您必须检查所有像素并将其四舍五入为黑色或白色。最简单的方法(如果只创建一个临时应用程序来对一些图像执行此操作)是使用GetPixel()SetPixel()方法:

Bitmap bmp = Bitmap.FromFile("image.png");
for(int i=0;i<bmp.Width;i++)
   for(int j=0;j<bmp.Height;j++)
      bmp.SetPixel(i,j, bmp.GetPixel(i,j).R > 127? Color.White: Color.Black); // as its gray I'm only checking Red

但是,如果您要处理大量图像(特别是大图像),或者它不是处理少数图像的临时应用程序,并且它将成为您应用程序的功能,那么上面的代码并不是您想要的请使用LockBits,因为它的速度非常慢:

 Bitmap bmp = Bitmap.FromFile("image.png"); 
 Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
 System.Drawing.Imaging.BitmapData bmpData = 
 bmp.LockBits(rect,System.Drawing.Imaging.ImageLockMode.ReadWrite,bmp.PixelFormat;
 IntPtr ptr = bmpData.Scan0;
 int bytes  = Math.Abs(bmpData.Stride) * bmp.Height;
 byte[] rgbValues = new byte[bytes];
 System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
 for (int counter = 0; counter < rgbValues.Length; counter += 4)
 {
    int c = rgbValues[counter] > 127 ? 255: 0;
    rgbValues[counter] = c;
    rgbValues[counter+1] = c;
    rgbValues[counter+2] = c;
 }
 System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
 bmp.UnlockBits(bmpData);