Aforge.net識別簡易數字驗證碼問題


參考:https://www.bbsmax.com/A/rV57LjWGdP/

https://blog.csdn.net/louislong007/article/details/47683035

簡易驗證碼樣例:

驗證碼識別流程:

首先進行圖像獲取:火狐瀏覽器,找到獲取驗證碼地址,獲取驗證碼圖像,傳遞給類,直接獲取到驗證碼!

驗證碼獲取:

         /// <summary>
         /// 通過GET方式獲取驗證碼
         /// </summary>
         /// <param name="Url">url</param>
         /// <param name="postDataStr">GET數據</param>
         /// <param name="cookie">GET容器</param>
         /// <returns></returns>
         public void SendDataByGET1(string Url, ref CookieContainer cookie)
         {
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
             if (cookie.Count == 0)
             {
                 request.CookieContainer = new CookieContainer();
                 cookie = request.CookieContainer;
             }
             else
             {
                 request.CookieContainer = cookie;
             }

             request.Method = "GET";
             request.ContentType = "text/html;charset=UTF-8";

             HttpWebResponse response = (HttpWebResponse)request.GetResponse();


             MemoryStream ms = null;
             using (var stream = response.GetResponseStream())
             {
                 Byte[] buffer = new Byte[response.ContentLength];
                 int offset = 0, actuallyRead = 0;
                 do
                 {
                     actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
                     offset += actuallyRead;
                 }
                 while (actuallyRead > 0);
                 ms = new MemoryStream(buffer);
             }

             b = new Bitmap(ms);

             //aforge只接受像素格式為24/32bpp的像素格式圖片,所以處理前,先進行格式轉化
             var bnew = new Bitmap(b.Width, b.Height,PixelFormat.Format24bppRgb);

             Graphics g = Graphics.FromImage(bnew);

             g.DrawImage(b, 0, 0);

             g.Dispose();
       
             pictureBox1.Image = bnew;
        
             //b = new Threshold(50).Apply(b);
             response.Close();
           
           string  strCookies = request.CookieContainer.GetCookieHeader(request.RequestUri); //把cookies轉換成字符串

        textBox2.Text=new VerificationCodeProcess().GetVerificationCode(bnew).ToString();

             //Stream myResponseStream = response.GetResponseStream();
             //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
             //string retString = myStreamReader.ReadToEnd();
             //myStreamReader.Close();
             //myResponseStream.Close();

           //MessageBox.Show(strCookies);
         }

 

驗證碼處理:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//
using System.Net;
using System.IO;
using Model;
using BLL;
using Model;
using AForge;
using AForge.Imaging;
using AForge.MachineLearning;
using System.Drawing.Drawing2D;
using AForge.Imaging.Filters;

namespace EmsService
{
    public class VerificationCodeProcess
    {
        public int GetVerificationCode(Bitmap bmp)
        {
            //灰度
            bmp = ToGray(bmp);
            //  MessageBox.Show(b.PixelFormat.ToString());
            //二進制//
            // pictureBox3.Image = ConvertToBinaryImage(new Bitmap(pictureBox2.Image));
            bmp = ConvertToBinaryImage(bmp);
            //   MessageBox.Show(b.PixelFormat.ToString());
            //分割
            List<Bitmap> bmList = ToResizeAndCenterIt(Crop_X(Crop_Y(bmp)));
            //二進制化
            StringBuilder sb = new StringBuilder();
            List<string> lls = PP(bmList);
            int top = Convert.ToInt32(lls[0]);
            int last = Convert.ToInt32(lls[2]);
            int result = 0;
            if (lls[1] == "-")
            {
                result = top - last;
            }
            else
            {
                result = top + last;
            }
            return result;
        }
        /// <summary>
        /// 灰度處理
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public Bitmap ToGray(Bitmap bmp)
        {
            Bitmap bm = new Bitmap(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);
                    // 利用公式計算灰度值  
                    // 根據YUV的顏色空間中,Y的分量的物理意義是點的亮度,由該值反映亮度等級,  
                    // 根據RGB和YUV顏色空間的變化關系可建立亮度Y與R、G、B三個顏色分量的對應:  
                    // Y=0.3R+0.59G+0.11B,以這個亮度值表達圖像的灰度值  
                    int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
                    Color newColor = Color.FromArgb(gray, gray, gray);
                    bm.SetPixel(i, j, newColor);
                }
            }
            return bm;
        }
        /// <summary>
        /// 二進制化
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public Bitmap ConvertToBinaryImage(Bitmap bmp)
        {
            Bitmap bm = new Bitmap(bmp.Width, bmp.Height);
            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 = 60;

            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);
                    bm.SetPixel(i, j, newColor);
                }
            }
            return bm;
        }
        /// <summary>
        /// 重置圖片的指定大小並且居中
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public List<Bitmap> ToResizeAndCenterIt(List<Bitmap> list, int w = 20, int h = 20)
        {
            List<Bitmap> resizeList = new List<Bitmap>();


            for (int i = 0; i < list.Count; i++)
            {
                //MessageBox.Show(list[i].PixelFormat.ToString());
                //反轉一下圖片
                var bnew10 = new Bitmap(list[i].Width, list[i].Height, PixelFormat.Format24bppRgb);

                Graphics g10 = Graphics.FromImage(bnew10);

                g10.DrawImage(list[i], 0, 0);

                g10.Dispose();
                list[i] = bnew10;

                list[i] = new Invert().Apply(list[i]);

                int sw = list[i].Width;
                int sh = list[i].Height;

                Crop corpFilter = new Crop(new Rectangle(0, 0, w, h));

                list[i] = corpFilter.Apply(list[i]);
                //var bnew1 = new Bitmap(list[i].Width, list[i].Height, PixelFormat.Format24bppRgb);

                //Graphics g1 = Graphics.FromImage(bnew1);

                //g1.DrawImage(list[i], 0, 0);

                //g1.Dispose();
                //再反轉回去
                list[i] = new Invert().Apply(list[i]);

                // //計算中心位置
                int centerX = (w - sw) / 2;
                int centerY = (h - sh) / 2;
                var bnew2 = new Bitmap(list[i].Width, list[i].Height, PixelFormat.Format24bppRgb);

                Graphics g2 = Graphics.FromImage(bnew2);

                g2.DrawImage(list[i], 0, 0);

                g2.Dispose();
                list[i] = new CanvasMove(new AForge.IntPoint(centerX, centerY), Color.White).Apply(list[i]);

                resizeList.Add(list[i]);
            }

            return resizeList;
        }

        /// <summary>
        /// 按照 Y 軸線 切割
        /// (丟棄等於號)
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public List<Bitmap> Crop_Y(Bitmap b)
        {
            var list = new List<Bitmap>();

            //統計每一列的“1”的個數,方便切除
            int[] cols = new int[b.Width];

            /*
               *  縱向切割
               */
            for (int x = 0; x < b.Width; x++)
            {
                for (int y = 0; y < b.Height; y++)
                {
                    //獲取當前像素點像素
                    var pixel = b.GetPixel(x, y);

                    //說明是黑色點
                    if (pixel.R == 0)
                    {
                        cols[x] = ++cols[x];
                    }
                }
            }

            int left = 0, right = 0;

            for (int i = 0; i < cols.Length; i++)
            {
                //說明該列有像素值(為了防止像素干擾,去噪后出現空白的問題,所以多判斷一下,防止切割成多個)
                if (cols[i] > 0 || (i + 1 < cols.Length && cols[i + 1] > 0))
                {
                    if (left == 0)
                    {
                        //切下來圖片的橫坐標left
                        left = i;
                    }
                    else
                    {
                        //切下來圖片的橫坐標right
                        right = i;
                    }
                }
                else
                {
                    //說明已經有切割圖了,下面我們進行切割處理
                    if ((left > 0 || right > 0))
                    {
                        Crop corp = new Crop(new Rectangle(left, 0, right - left + 1, b.Height));

                        var small = corp.Apply(b);

                        //居中,將圖片放在20*50的像素里面

                        list.Add(small);
                    }

                    left = right = 0;
                }
            }

            return list;
        }

        /// <summary>
        /// 按照 X 軸線 切割
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public List<Bitmap> Crop_X(List<Bitmap> list)
        {
            var corplist = new List<Bitmap>();

            //再對分割的圖進行上下切割,取出上下的白邊
            foreach (var segb in list)
            {
                //統計每一行的“1”的個數,方便切除
                int[] rows = new int[segb.Height];

                /*
                 *  橫向切割
                   */
                for (int y = 0; y < segb.Height; y++)
                {
                    for (int x = 0; x < segb.Width; x++)
                    {
                        //獲取當前像素點像素
                        var pixel = segb.GetPixel(x, y);

                        //說明是黑色點
                        if (pixel.R == 0)
                        {
                            rows[y] = ++rows[y];
                        }
                    }
                }
                int bottom = 0, top = 0;

                for (int y = 0; y < rows.Length; y++)
                {
                    //說明該行有像素值(為了防止像素干擾,去噪后出現空白的問題,所以多判斷一下,防止切割成多個)
                    if (rows[y] > 0 || (y + 1 < rows.Length && rows[y + 1] > 0))
                    {
                        if (top == 0)
                        {
                            //切下來圖片的top坐標
                            top = y;
                        }
                        else
                        {
                            //切下來圖片的bottom坐標
                            bottom = y;
                        }
                    }
                    else
                    {
                        //說明已經有切割圖了,下面我們進行切割處理
                        if ((top > 0 || bottom > 0) && bottom - top > 0)
                        {
                            Crop corp = new Crop(new Rectangle(0, top, segb.Width, bottom - top + 1));

                            var small = corp.Apply(segb);

                            corplist.Add(small);
                        }
                        top = bottom = 0;
                    }
                }
            }

            return corplist;
        }
        //模式匹配
        public List<string> PP(List<Bitmap> list)
        {
            var files = Directory.GetFiles(Environment.CurrentDirectory + "\\temp\\");

            var templateList = files.Select(i => { return new Bitmap(i); }).ToList();
            var templateListFileName = files.Select(i => { return i.Substring(i.Length - 5).Substring(0, 1); }).ToList();

            var result = new List<string>();

            ExhaustiveTemplateMatching templateMatching = new ExhaustiveTemplateMatching(0.9f);

            //這里面有四張圖片,進行四張圖的模板匹配
            for (int i = 0; i < 3; i++)
            {
                float max = 0;
                int index = 0;

                for (int j = 0; j < templateList.Count; j++)
                {
                    var compare = templateMatching.ProcessImage(list[i], templateList[j]);

                    if (compare.Length > 0 && compare[0].Similarity > max)
                    {
                        //記錄下最相似的
                        max = compare[0].Similarity;
                        index = j;
                    }
                }

                result.Add(templateListFileName[index]);
            }
            return result;
        }

    }
}

效果圖:

 

 

 

         /// <summary>         /// 通過GET方式獲取驗證碼         /// </summary>         /// <param name="Url">url</param>         /// <param name="postDataStr">GET數據</param>         /// <param name="cookie">GET容器</param>         /// <returns></returns>         public void SendDataByGET1(string Url, ref CookieContainer cookie)         {             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);             if (cookie.Count == 0)             {                 request.CookieContainer = new CookieContainer();                 cookie = request.CookieContainer;             }             else             {                 request.CookieContainer = cookie;             }
             request.Method = "GET";             request.ContentType = "text/html;charset=UTF-8";
             HttpWebResponse response = (HttpWebResponse)request.GetResponse();

             MemoryStream ms = null;             using (var stream = response.GetResponseStream())             {                 Byte[] buffer = new Byte[response.ContentLength];                 int offset = 0, actuallyRead = 0;                 do                 {                     actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);                     offset += actuallyRead;                 }                 while (actuallyRead > 0);                 ms = new MemoryStream(buffer);             }
             b = new Bitmap(ms);
             //aforge只接受像素格式為24/32bpp的像素格式圖片,所以處理前,先進行格式轉化             var bnew = new Bitmap(b.Width, b.Height,PixelFormat.Format24bppRgb);
             Graphics g = Graphics.FromImage(bnew);
             g.DrawImage(b, 0, 0);
             g.Dispose();         //    //                    ////灰度         //    Bitmap temp;         //    temp = AForge.Imaging.Image.Clone(b, b.PixelFormat);         //    b = new Grayscale(0.2125, 0.7154, 0.0721).Apply(b);         //    //二值化            // b = new Threshold(50).Apply(b);                  pictureBox1.Image = bnew;                     //b = new Threshold(50).Apply(b);             response.Close();                      string  strCookies = request.CookieContainer.GetCookieHeader(request.RequestUri); //把cookies轉換成字符串
        textBox2.Text=new VerificationCodeProcess().GetVerificationCode(bnew).ToString();
             //Stream myResponseStream = response.GetResponseStream();             //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));             //string retString = myStreamReader.ReadToEnd();             //myStreamReader.Close();             //myResponseStream.Close();
           //MessageBox.Show(strCookies);         }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM