c#图像灰度处理及二值化处理代码解释

这段是我的代码 请高手给重点字段的解释(作用,效果) private void btn_convert_Click(object sender, EventArgs e) { Bitmap img1 = (Bitmap)pictureBox1.Image; pictureBox2.Image = GrayByPixels(img1); Double d = 0.8; Bitmap img2 = (Bitmap)pictureBox2.Image; pictureBox3.Image = BitmapToBlack(img2, d); } public Bitmap GrayByPixels(Bitmap bmpcode) { bmpcode = new Bitmap(bmpcode); for (int i = 0; i < bmpcode.Height; i++) { for (int j = 0; j < bmpcode.Width; j++) { int tmpValue = GetGrayNumColor(bmpcode.GetPixel(j, i)); bmpcode.SetPixel(j, i, Color.FromArgb(tmpValue, tmpValue, tmpValue)); } } return bmpcode; } private int GetGrayNumColor(System.Drawing.Color codecolor) { return (codecolor.R * 19595 + codecolor.G * 38469 + codecolor.B * 7472) >> 16; } public static Bitmap BitmapToBlack(Bitmap img, Double hsb) { 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);//将 Bitmap 锁定到系统内存中 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() >= hsb) scan[x / 8] |= (byte)(0x80 >> (x % 8));//亮度值和原来比较,二值化处理 } Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length); } bmp.UnlockBits(data);//将 Bitmap 锁定到系统内存中 return bmp; }

第1个回答  2019-06-23
这代码写的很低效,不过还算清晰。
灰度处理那个很简单吧,基本上C#都自动帮你做了,你那代码就是手动遍历其中每个像素然后读取其灰度值(这里代码偷懒直接让C#帮忙计算了)然后重新把像素设置为RGB都是灰度值的颜色而已。
二值化的其实也不复杂,也是逐个遍历像素,判断某个像素的亮度是否大于给定阈值,如果大于则设置为白色否则设置为黑色。唯一有点麻烦的是要把8个像素合并到一个字节里面,于是代码里面搞了个scan数组,然后八个像素为一组填进去,每个像素占字节的一个位(白1黑0)。使用位运算0x80
>>
(x
%
8)保证像素从左到右依次保存在字节的8个位上。你这个二值化代码回填像素信息的时候用的是Marshal的字节拷贝而已,你只要知道了位图的结构这个理解也很简单。
相似回答