(ImageMagick + tesseract - ocr) 를 사용 하여 이미지 인증 코드 인식 인 스 턴 스 를 실현 합 니 다.

최근 에 무인 당직 시스템 을 만 들 때 자동 으로 로그 인 할 수 있 고 로그 인 할 때 인증 코드 를 입력 해 야 하기 때문에 인증 코드 인식 기술 을 연 구 했 습 니 다. 그렇지 않 으 면 저 는 무인 당직 시스템 의 역할 이 없습니다.현재 알파벳 과 숫자의 식별 만 테스트 했 습 니 다. 정확 도 는 괜 찮 습 니 다. 하하, 저 만 사용 할 수 있 습 니 다 ~ ~ 중국어 의 식별 은 제 지난 글 을 참고 할 수 있 습 니 다. 오픈 소스 프로그램 (ImageMagick + tesseract - ocr) 을 이용 하여 이미지 인증 코드 인식 을 실현 할 수 있 습 니 다.
인증 코드 식별 율 은 다음 그림 과 같다. (정확 도 는 괜 찮 죠?)
좋 습 니 다. 본론 으로 들 어가 서 빨리 소스 코드 를 올 리 세 요 ~ ~, 부족 한 점 많이 양해 해 주세요.
메모: 인증 코드 인식 류 를 사용 하기 전에 첫째, ImageMagick 을 설치 하 십시오. 둘째, tesseract - 2.04. exe. tar. gz 와 tesseract - 2.00. eng. tar. gz 를 다운로드 하고 내용 을 tesseract 디 렉 터 리 에 압축 을 풀 고 tesseract 디 렉 터 리 를 응용 프로그램 아래 (debug 디 렉 터 리 아래) 로 복사 해 야 합 니 다.
1. 이미지 인식, 식별 유형 검증 
    /// <summary>
    ///     ,    
    /// </summary>
    public class Identify
    {
        /// <summary>
        ///     :         、  ,          
         /// </summary>
        /// <param name="img_path">        </param>
        /// <param name="save_dir">        </param>
        /// <param name="scale">      (     :100~1000)-(  :       )</param>
        /// <returns></returns>
        public static string StartIdentifyingCaptcha(string img_path, string save_dir,int scale)
        {
            return StartIdentifyingCaptcha(img_path, save_dir, 4, 0, scale);
        }
        /// <summary>
        ///     :         、  ,          
         /// </summary>
        /// <param name="img_path">        </param>
        /// <param name="save_dir">        </param>
        /// <param name="content_type">    (0:    1:    2:        3:   ,4、     )-(  :       )</param>
        /// <param name="content_length">    (  :       )</param>
        /// <param name="scale">      (     :100~1000)-(  :       )</param>
        /// <returns></returns>
        public static string StartIdentifyingCaptcha(string img_path, string save_dir, byte content_type, int content_length, int scale)
        {
            string captcha = "";            //       

            //int captcha_length = 6;         //      (  :       )

            //int scale = 730;                //       (  :       )

            do
            {
                //      ( 、  ImageMagick, 、  tesseract        )
                Common.StartProcess("cmd.exe", new string[] { "cd tesseract" ,

                                                                    //     
                                                                    String.Format(@"convert.exe -compress none -depth 8 -alpha off -scale {0}% -colorspace gray {1} {2}\captcha.tif",scale,img_path,save_dir),
                                
                                                                    //     
                                                                    String.Format(@"tesseract.exe {0}\captcha.tif {0}\result",save_dir),

                                                                    "exit"});

                //         
                StreamReader reader = new StreamReader(String.Format(@"{0}\result.txt", save_dir));

                captcha = reader.ReadLine().Trim();

                reader.Close();
                
                //     
                string pattern = "";

                //    
                if (content_type == 0)
                {
                    pattern = (content_length > 0) ? "^[0-9]{" + content_length + "}$" : "^[0-9]+$";
                }
                //    
                else if (content_type == 1)
                {
                    pattern = (content_length > 0) ? "^[a-zA-Z]{" + content_length + "}$" : "^[a-zA-Z]+$";
                }
                //        
                else if (content_type == 2)
                {
                    pattern = (content_length > 0) ? "^[a-zA-Z0-9]{" + content_length + "}$" : "^[a-zA-Z0-9]+$";
                }
                //    
                else if (content_type == 3)
                {
                    pattern = (content_length > 0) ? "^[\u4e00-\u9fa5]{" + content_length + "}$" : "^[\u4e00-\u9fa5]+$";
                }
                //      
                else
                {
                    pattern = (content_length > 0) ? "^[A-Za-z0-9\u4e00-\u9fa5]{" + content_length + "}$" : "^[A-Za-z0-9\u4e00-\u9fa5]+$";
                }


                //     ,          
                if (pattern != "" && !Regex.IsMatch(captcha, pattern))
                {
                    captcha = "";

                    scale++;
                }

                //      9  ,     ,      ,    
                if (scale > 900)
                {
                    captcha = "";

                    break;
                }

            } while (captcha == "");

            return captcha;
        }
    }

2. C\# 에서 명령 행 명령 을 수행 하 는 함수
public class Common
    {

        #region     :     C#          
        /// <summary>
        ///     :     C#          
        /// </summary>
        /// <param name="startFileName">        </param>
        /// <param name="commands">     </param>
        /// <returns></returns>
        public static string StartProcess(string startFileName, string[] commands)
        {
            //    Process ,        
            Process p = new Process();

            //Process    StartInfo  ,   ProcessStartInfo ,          ,

            //             :

            //     
            p.StartInfo.FileName = startFileName;

            //  Shell   
            p.StartInfo.UseShellExecute = false;

            //       
            p.StartInfo.RedirectStandardInput = true;

            //       
            p.StartInfo.RedirectStandardOutput = true;

            //       
            p.StartInfo.RedirectStandardError = true;

            //       
            p.StartInfo.CreateNoWindow = true;

            //                 。

            //              
            p.Start();

            //        
            foreach (string command in commands)
            {
                p.StandardInput.WriteLine(command);
            }

            //            
            return p.StandardOutput.ReadToEnd();
        }
        #endregion
    }

좋은 웹페이지 즐겨찾기