分享C#識別圖片上的數字


通過Emgu實現對圖片上的數字進行識別。
前期步驟:
1.下載Emgu安裝文件,我的版本是2.4.2.1777。3.0版本則實現對中文的支持。
2.安裝后需填寫環境變量,環境變量Path值后加入Emgu安裝路徑到bin下。如C:\Emgu\emgucv-windows-x86-gpu 2.4.2.1777\bin;
3.在bin下查找需要的dll如Emgu.CV.dll與Emgu.CV.OCR.dll等。
4.將C:\Emgu\emgucv-windows-x86-gpu 2.4.2.1777\bin下的文件夾tessdata賦值到程序運行目錄下。
注:安裝后的Emgu路徑下有C#版本的demo可供參考
關鍵代碼:
將需要的dll導入到項目中。

private static Tesseract _ocr;//創建識別對象
//傳入圖片進行識別
public static string ORC_(Bitmap img)
        {
            //""標示OCR識別調用失敗
            string re = "";
            if (img == null)
                return re;
            else
            {
 
 
                Bgr drawColor = new Bgr(Color.Blue);
                try
                {
                    Image<Bgr, Byte> image = new Image<Bgr, byte>(img);
 
 
                    using (Image<Gray, byte> gray = image.Convert<Gray, Byte>())
                    {
                        _ocr.Recognize(gray);
                        Tesseract.Charactor[] charactors = _ocr.GetCharactors();
                        foreach (Tesseract.Charactor c in charactors)
                        {
                            image.Draw(c.Region, drawColor, 1);
                        }
 
 
                        re = _ocr.GetText();
 
 
                    }
                    return re;
                }
                catch (Exception ex)
                {
                     
                    return re;
                }
            }
        }
 
//識別方法如點擊按鈕識別
private void btnXIdentification_Click(object sender, EventArgs e)
        {
            try
            {
                _ocr = new Tesseract(@"C:\Emgu\emgucv-windows-x86-gpu 2.4.2.1777\bin\tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_CUBE_COMBINED);//方法第一個參數可為""表示通過環境變量調用字庫,第二個參數表示字庫的文件,第三個表示識別方式,可看文檔與資料查找。
                _ocr.SetVariable("tessedit_char_whitelist", "0123456789X");//此方法表示只識別1234567890與x字母
                string result = "";
                Bitmap bitmap = new Bitmap(_emguImage.ToBitmap());
                bitmap = BrightnessP(bitmap, Convert.ToInt32(this.textBoxX3.Text));//圖片加亮處理
                bitmap = KiContrast(bitmap, Convert.ToInt32(this.textBoxX2.Text));//調整對比對
                this.pictureBox3.Image = bitmap;
                result = ORC_(bitmap);
                this.textBoxX1.Text = result;
                _ocr.Dispose();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
 
/// <summary>  
        /// 增加圖像亮度  
        /// </summary>  
        /// <param name="a"></param>  
 
        /// <param name="v"></param>  
        /// <returns></returns>  
        public static Bitmap BrightnessP(Bitmap a, int v)
        {
            System.Drawing.Imaging.BitmapData bmpData = a.LockBits(new Rectangle(0, 0, a.Width, a.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            int bytes = a.Width * a.Height * 3;
            IntPtr ptr = bmpData.Scan0;
            int stride = bmpData.Stride;
            unsafe
            {
                byte* p = (byte*)ptr;
                int temp;
                for (int j = 0; j < a.Height; j++)
                {
                    for (int i = 0; i < a.Width * 3; i++, p++)
                    {
                        temp = (int)(p[0] + v);
                        temp = (temp > 255) ? 255 : temp < 0 ? 0 : temp;
                        p[0] = (byte)temp;
                    }
                    p += stride - a.Width * 3;
                }
            }
            a.UnlockBits(bmpData);
            return a;
        }
        ///<summary>
        ///圖像對比度調整
        ///</summary>
        ///<param name="b">原始圖</param>
        ///<param name="degree">對比度[-100, 100]</param>
        ///<returns></returns>
        public static Bitmap KiContrast(Bitmap b, int degree)
        {
            if (b == null)
            {
                return null;
            }
            if (degree < -100) degree = -100;
            if (degree > 100) degree = 100;
            try
            {
                double pixel = 0;
                double contrast = (100.0 + degree) / 100.0;
                contrast *= contrast;
                int width = b.Width;
                int height = b.Height;
                BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                unsafe
                {
                    byte* p = (byte*)data.Scan0;
                    int offset = data.Stride - width * 3;
                    for (int y = 0; y < height; y++)
                    {
                        for (int x = 0; x < width; x++)
                        {
                            // 處理指定位置像素的對比度
                            for (int i = 0; i < 3; i++)
                            {
                                pixel = ((p / 255.0 - 0.5) * contrast + 0.5) * 255;
                                if (pixel < 0) pixel = 0;
                                if (pixel > 255) pixel = 255;
                                p = (byte)pixel;
                            } // i
                            p += 3;
                        } // x
                        p += offset;
                    } // y
                }
                b.UnlockBits(data);
                return b;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

OEM_TESSERACT_ONLY,           // Run Tesseract only - fastest運行只TESSERACT - 最快
OEM_CUBE_ONLY,                // Run Cube only - better accuracy, but slower只運行立方 - 更好的精度,但速度較慢
OEM_TESSERACT_CUBE_COMBINED,  // Run both and combine results - best accuracy運行和結果相結合 - 最佳精度
OEM_DEFAULT                   // Specify this mode when calling init_*(),指定此模式下,當調用init_*()


免責聲明!

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



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