工程是一门科学,科学是严谨的。

验证码识别技术研究(1)

 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             #endregion
23 
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                     else
38                     {
39                         color = Color.FromArgb(0, 0, 0);
40                     }
41                     g.DrawLine(new Pen(color, 1), x, y, x + 1, y + 1);
42                 }
43             }
44             #endregion
45 
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             #endregion
55 
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);//灰度平均值

 灰度算法公式:

G = (R * 299 + G * 587 + B * 114 + 500) / 1000

 

posted @ 2013-03-07 19:15  大圣的笑  阅读(370)  评论(0编辑  收藏  举报