首页 > 代码库 > 二值化

二值化

 //二值化
      public static void Binarize(Bitmap sourceBitmap)
            {
                if (sourceBitmap != null)
                {
                    string Rbrthreshold = Microsoft.VisualBasic.Interaction.InputBox("请输入一个-255~255之间的阀值。\n\n注:正负值可使图像二值化为不同的“黑白效果”",
                        "二值化阀值设置", "70", 100, 100);
                    if (Rbrthreshold == "" || Convert.ToInt16(Rbrthreshold) < -255 || Convert.ToInt16(Rbrthreshold) > 255)
                    {
                        MessageBox.Show("阀值必须在-255~255之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        Rectangle rect = new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height);
                        System.Drawing.Imaging.BitmapData bmpData = sourceBitmap.LockBits(rect, ImageLockMode.ReadWrite, sourceBitmap.PixelFormat);
                        unsafe//指针法,对像素操作
                        {
                            int blue;
                            int rgbth = Convert.ToInt16(Rbrthreshold);
                            byte* ptr = (byte*)(bmpData.Scan0);
                            for (int i = 0; i < bmpData.Height; i++)
                            {
                                for (int j = 0; j < bmpData.Width; j++)
                                {
                                    if (rgbth > 0)
                                    {
                                        blue = (int)(ptr[0] < System.Math.Abs(rgbth) ? 0 : 255);
                                    }
                                    else
                                    {
                                        blue = (int)(ptr[0] > System.Math.Abs(rgbth) ? 0 : 255);
                                    }
                                    ptr[0] = ptr[1] = ptr[2] = (byte)(blue);
                                    ptr += 3;
                                }
                                ptr += bmpData.Stride - bmpData.Width * 3;

                            }
                        }

                        sourceBitmap.UnlockBits(bmpData);

                    }
                }
                else
                {
                    MessageBox.Show("无图像可处理", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                }

图像的二值化的性质类似于图像的灰度化处理,即将原来色彩丰富的图像变得简单,而二值化则使图像的色彩变得更少,只有两种颜色:黑白。于是,这种图像的像素颜色只需1位二进制值表示。图像存储数据量急剧减少,而且可使一些图像处理的算法简化或处理的速度提高。

二值化