1 string imgpName = @"005"; 2 Image image = Image.FromFile(@"G:\" + imgpName + @".jpg"); 3 Image img = (Image)image.Clone(); 4 Bitmap bmp = new Bitmap((Image)image.Clone()); 5 int gray = 0; 6 Graphics g = Graphics.FromImage(image); 7 int sum = 0; 8 int[] zf = new int[256];//灰階數組 9 10 #region 灰階平均值11 for (int x = 0; x < bmp.Width; x++)12 {13 for (int y = 0; y < bmp.Height; y++)14 {15 //灰階演算法16 gray = (bmp.GetPixel(x, y).R * 299 + bmp.GetPixel(x, y).G * 587 + bmp.GetPixel(x, y).B * 114 + 500) / 1000;17 zf[gray]++;18 sum += gray;19 }20 }21 int avg = sum / (bmp.Width * bmp.Height);22 #endregion23 24 #region 以獲得的灰階平均值為閥值,對映像進行二值化處理25 for (int x = 0; x < bmp.Width; x++)26 {27 for (int y = 0; y < bmp.Height; y++)28 {29 gray = (bmp.GetPixel(x, y).R * 299 + bmp.GetPixel(x, y).G * 587 + bmp.GetPixel(x, y).B * 114 + 500) / 1000;30 zf[gray]++;31 sum += gray;32 Color color = new Color();33 if (gray > avg)34 {35 color = Color.FromArgb(255, 255, 255);36 }37 else38 {39 color = Color.FromArgb(0, 0, 0);40 }41 g.DrawLine(new Pen(color, 1), x, y, x + 1, y + 1);42 }43 }44 #endregion45 46 #region 長條圖繪製47 Graphics gg = Graphics.FromImage(img);48 //string k = ((int)(bmp.Height * 0.5) / zf.Max()).ToString();49 for (int i = 0; i < zf.Length; i++)50 {51 Pen p = new Pen(Color.Red, 1);52 gg.DrawLine(p, i, 0, i, zf[i]);53 }54 #endregion55 56 img.Save(@"G:\" + imgpName + @"長條圖.jpg");57 gg.Dispose();58 image.Save(@"G:\" + imgpName + @"二值化圖.jpg");59 image.Dispose();60 g.Dispose();61 MessageBox.Show("OK!\nGray_AVG:" + avg);//灰階平均值