/// <summary> /// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255 /// </summary> /// <param name="bmp"></param> /// <returns></returns> public static Bitmap ConvertTo1Bpp1(Bitmap bmp) { int average = 0; for ( int i = 0; i < bmp.Width; i++) { for ( int j = 0; j < bmp.Height; j++) { Color color = bmp.GetPixel(i, j); average += color.B; } } average = ( int )average / (bmp.Width * bmp.Height); for ( int i = 0; i < bmp.Width; i++) { for ( int j = 0; j < bmp.Height; j++) { //获取该点的像素的RGB的颜色 Color color = bmp.GetPixel(i, j); int value = 255 - color.B; Color newColor = value > average ? Color.FromArgb(0, 0, 0): Color.FromArgb(255, 255, 255); bmp.SetPixel(i, j, newColor); } } return bmp; } /// <summary> /// 图像二值化2 /// </summary> /// <param name="img"></param> /// <returns></returns> public static Bitmap ConvertTo1Bpp2(Bitmap img) { int w = img.Width; int h = img.Height; Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed); BitmapData data = bmp.LockBits( new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed); for ( int y = 0; y < h; y++) { byte [] scan = new byte [(w + 7) / 8]; for ( int x = 0; x < w; x++) { Color c = img.GetPixel(x, y); if (c.GetBrightness() >= 0.5) scan[x / 8] |= ( byte )(0x80 >> (x % 8)); } Marshal.Copy(scan, 0, (IntPtr)(( int )data.Scan0 + data.Stride * y), scan.Length); } return bmp; } |