Exemplo n.º 1
0
        /// <summary>
        /// OCR処理を実施します
        /// </summary>
        /// <param name="InPath">入力パス</param>
        /// <param name="NgPath">NG出力パス</param>
        /// <param name="rePath">OCR変換結果出力パス</param>
        /// <param name="FormatName">書式ファイル名</param>
        /// <param name="fCnt">書式ファイルの件数</param>
        private void ocrMain(string InPath, string NgPath, string rePath, string FormatName, int fCnt)
        {
            IEngine en       = null;            // OCRエンジンのインスタンスを保持
            string  ocr_csv  = string.Empty;    // OCR変換出力CSVファイル
            int     _okCount = 0;               // OCR変換画像枚数
            int     _ngCount = 0;               // フォーマットアンマッチ画像枚数
            string  fnm      = string.Empty;    // ファイル名

            try
            {
                // 指定された出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(rePath) == false)
                {
                    System.IO.Directory.CreateDirectory(rePath);
                }

                // 指定されたNGの場合の出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(NgPath) == false)
                {
                    System.IO.Directory.CreateDirectory(NgPath);
                }

                // OCRエンジンのインスタンスの生成・取得
                en = EngineFactory.GetEngine();
                if (en == null)
                {
                    // エンジンが他で取得されている場合は、Release() されるまで取得できない
                    System.Console.WriteLine("SDKは使用中です");
                    return;
                }

                //オーナーフォームを無効にする
                this.Enabled = false;

                //プログレスバーを表示する
                frmPrg frmP = new frmPrg();
                frmP.Owner = this;
                frmP.Show();

                IFormatList FormatList;
                IFormat     Format;
                IField      Field;
                int         nPage;
                int         ocrPage   = 0;
                int         fileCount = 0;

                // フォーマットのロード・設定
                FormatList = en.FormatList;
                FormatList.Add(FormatName);

                // tifファイルの認識
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
                {
                    nPage = 1;
                    while (true)
                    {
                        try
                        {
                            // 対象画像を設定する
                            en.SetBitmap(files, nPage);

                            //プログレスバー表示
                            fileCount++;
                            frmP.Text          = "OCR変換処理実行中 " + fileCount.ToString() + "/" + fCnt.ToString();
                            frmP.progressValue = fileCount * 100 / fCnt;
                            frmP.ProgressStep();
                        }
                        catch (IDRException ex)
                        {
                            // ページ読み込みエラー
                            if (ex.No == ErrorCode.IDR_ERROR_FORM_FILEREAD)
                            {
                                // ページの終了
                                break;
                            }
                            else
                            {
                                // 例外のキャッチ
                                MessageBox.Show("例外が発生しました:Error No ={0:X}", ex.No.ToString());
                            }
                        }

                        //////Console.WriteLine("-----" + strImageFile + "の" + nPage + "ページ-----");
                        // 現在ロードされている画像を自動的に傾き補正する
                        en.AutoSkew();

                        // 傾き角度の取得
                        double angle = en.GetSkewAngle();
                        //////System.Console.WriteLine("時計回りに" + angle + "度傾き補正を行いました");

                        try
                        {
                            // 現在ロードされている画像を自動回転してマッチする番号を取得する
                            Format = en.MatchFormatRotate();
                            int direct = en.GetRotateAngle();

                            //画像ロード
                            RasterCodecs.Startup();
                            RasterCodecs cs = new RasterCodecs();
                            //RasterImage img;

                            // 描画時に使用される速度、品質、およびスタイルを制御します。
                            //RasterPaintProperties prop = new RasterPaintProperties();
                            //prop = RasterPaintProperties.Default;
                            //prop.PaintDisplayMode = RasterPaintDisplayModeFlags.Resample;
                            //leadImg.PaintProperties = prop;

                            RasterImage img = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);

                            RotateCommand rc = new RotateCommand();
                            rc.Angle     = (direct) * 90 * 100;
                            rc.FillColor = new RasterColor(255, 255, 255);
                            rc.Flags     = RotateCommandFlags.Resize;
                            rc.Run(img);
                            //rc.Run(leadImg.Image);

                            //cs.Save(leadImg.Image, files, RasterImageFormat.Tif, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);
                            cs.Save(img, files, RasterImageFormat.CcittGroup4, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);

                            // マッチしたフォーマットに登録されているフィールド数を取得
                            int fieldNum = Format.NumOfFields;
                            int matchNum = Format.FormatNo + 1;
                            //////System.Console.WriteLine(matchNum + "番目のフォーマットがマッチ");
                            int i = 1;
                            ocr_csv = string.Empty;

                            // ファイルの先頭フィールドにファイル番号をセットします
                            ocr_csv = System.IO.Path.GetFileNameWithoutExtension(files) + ",";

                            // ファイルに画像ファイル名フィールドを付加します
                            ocr_csv += System.IO.Path.GetFileName(files);

                            // 認識されたフィールドを順次読み出します
                            Field = Format.Begin();
                            while (Field != null)
                            {
                                //カンマ付加
                                if (ocr_csv != string.Empty)
                                {
                                    ocr_csv += ",";
                                }

                                // 指定フィールドを認識し、テキストを取得
                                string strText = Field.ExtractFieldText();
                                ocr_csv += strText;

                                // 次のフィールドの取得
                                Field = Format.Next();
                                i    += 1;
                            }

                            //出力ファイル
                            System.IO.StreamWriter outFile = new System.IO.StreamWriter(InPath + System.IO.Path.GetFileNameWithoutExtension(files) + ".csv", false, System.Text.Encoding.GetEncoding(932));
                            outFile.WriteLine(ocr_csv);
                            outFile.Close();

                            //OCR変換枚数カウント
                            _okCount++;
                        }
                        catch (IDRWarning ex)
                        {
                            // Engine.MatchFormatRotate() で
                            // フォーマットにマッチしなかった場合の処理
                            if (ex.No == ErrorCode.IDR_WARN_FORM_NO_MATCH)
                            {
                                // NGフォルダへ移動する
                                System.IO.File.Move(files, NgPath + "E" + System.IO.Path.GetFileName(files));

                                //NG枚数カウント
                                _ngCount++;
                            }
                        }

                        ocrPage++;
                        nPage += 1;
                    }
                }

                // いったんオーナーをアクティブにする
                this.Activate();

                // 進行状況ダイアログを閉じる
                frmP.Close();

                // オーナーのフォームを有効に戻す
                this.Enabled = true;

                string        finMessage = string.Empty;
                StringBuilder sb         = new StringBuilder();

                // NGメッセージ
                if (_ngCount > 0)
                {
                    MessageBox.Show("OCR認識を正常に行うことが出来なかった画像があります。確認してください。", "確認", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // 終了メッセージ
                sb.Clear();
                sb.Append("OCR認識処理が終了しました。");
                sb.Append("引き続き修正確認&受け渡しデータ作成を行ってください。");
                sb.Append(Environment.NewLine);
                sb.Append(Environment.NewLine);
                sb.Append("OK件数 : ");
                sb.Append(_okCount.ToString());
                sb.Append(Environment.NewLine);
                sb.Append("NG件数 : ");
                sb.Append(_ngCount.ToString());
                sb.Append(Environment.NewLine);

                MessageBox.Show(sb.ToString(), "処理終了", MessageBoxButtons.OK, MessageBoxIcon.Information);
                // OCR変換画像とCSVデータをOCR結果出力フォルダへ移動する
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.*"))
                {
                    System.IO.File.Move(files, rePath + System.IO.Path.GetFileName(files));
                }

                FormatList.Delete(0);
            }
            catch (System.Exception ex)
            {
                // 例外のキャッチ
                string errMessage = string.Empty;
                errMessage += "System例外が発生しました:" + Environment.NewLine;
                errMessage += "必要なDLL等が実行モジュールと同ディレクトリに存在するか確認してください。:" + Environment.NewLine;
                errMessage += ex.Message.ToString();
                MessageBox.Show(errMessage, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                en.Release();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// OCR処理を実施します
        /// </summary>
        /// <param name="InPath">入力パス</param>
        /// <param name="NgPath">NG出力パス</param>
        /// <param name="rePath">OCR変換結果出力パス</param>
        /// <param name="FormatName">書式ファイル名</param>
        /// <param name="fCnt">書式ファイルの件数</param>
        private void ocrMain(string InPath, string NgPath, string rePath, string FormatName, int fCnt)
        {
            IEngine en        = null;                                                // OCRエンジンのインスタンスを保持
            string  ocr_csv   = string.Empty;                                        // OCR変換出力CSVファイル
            int     _ngCount  = 0;                                                   // フォーマットアンマッチ画像枚数
            string  fnm       = string.Empty;                                        // ファイル名
            string  path2Fdir = Properties.Settings.Default.instDir + global.DIR_2F; // 2F伝票フォルダ

            try
            {
                // 指定された出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(rePath) == false)
                {
                    System.IO.Directory.CreateDirectory(rePath);
                }

                // 指定されたNGの場合の出力先フォルダがなければ作成する
                if (System.IO.Directory.Exists(NgPath) == false)
                {
                    System.IO.Directory.CreateDirectory(NgPath);
                }

                // 2F伝票フォルダがなければ作成する
                if (System.IO.Directory.Exists(path2Fdir) == false)
                {
                    System.IO.Directory.CreateDirectory(path2Fdir);
                }

                // OCRエンジンのインスタンスの生成・取得
                en = EngineFactory.GetEngine();
                if (en == null)
                {
                    // エンジンが他で取得されている場合は、Release() されるまで取得できない
                    System.Console.WriteLine("SDKは使用中です");
                    return;
                }

                //オーナーフォームを無効にする
                this.Enabled = false;

                //プログレスバーを表示する
                frmPrg frmP = new frmPrg();
                frmP.Owner = this;
                frmP.Show();

                IFormatList FormatList;
                IFormat     Format;
                IField      Field;
                int         nPage;
                int         ocrPage   = 0;
                int         fileCount = 0;

                // フォーマットのロード・設定
                FormatList = en.FormatList;
                FormatList.Add(FormatName);

                // tifファイルの認識
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.tif"))
                {
                    nPage = 1;
                    while (true)
                    {
                        try
                        {
                            // 対象画像を設定する
                            en.SetBitmap(files, nPage);

                            //プログレスバー表示
                            fileCount++;
                            frmP.Text          = "OCR変換処理実行中 " + fileCount.ToString() + "/" + fCnt.ToString();
                            frmP.progressValue = fileCount * 100 / fCnt;
                            frmP.ProgressStep();
                        }
                        catch (IDRException ex)
                        {
                            // ページ読み込みエラー
                            if (ex.No == ErrorCode.IDR_ERROR_FORM_FILEREAD)
                            {
                                // ページの終了
                                break;
                            }
                            else
                            {
                                // 例外のキャッチ
                                MessageBox.Show("例外が発生しました:Error No ={0:X}", ex.No.ToString());
                            }
                        }

                        //////Console.WriteLine("-----" + strImageFile + "の" + nPage + "ページ-----");
                        // 現在ロードされている画像を自動的に傾き補正する
                        en.AutoSkew();

                        // 傾き角度の取得
                        double angle = en.GetSkewAngle();
                        //////System.Console.WriteLine("時計回りに" + angle + "度傾き補正を行いました");

                        try
                        {
                            // 現在ロードされている画像を自動回転してマッチする番号を取得する
                            Format = en.MatchFormatRotate();
                            int direct = en.GetRotateAngle();

                            //画像ロード
                            RasterCodecs.Startup();
                            RasterCodecs cs = new RasterCodecs();
                            //RasterImage img;

                            // 描画時に使用される速度、品質、およびスタイルを制御します。
                            //RasterPaintProperties prop = new RasterPaintProperties();
                            //prop = RasterPaintProperties.Default;
                            //prop.PaintDisplayMode = RasterPaintDisplayModeFlags.Resample;
                            //leadImg.PaintProperties = prop;

                            RasterImage img = cs.Load(files, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);

                            RotateCommand rc = new RotateCommand();
                            rc.Angle     = (direct) * 90 * 100;
                            rc.FillColor = new RasterColor(255, 255, 255);
                            rc.Flags     = RotateCommandFlags.Resize;
                            rc.Run(img);
                            //rc.Run(leadImg.Image);

                            //cs.Save(leadImg.Image, files, RasterImageFormat.Tif, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);
                            cs.Save(img, files, RasterImageFormat.CcittGroup4, 0, 1, 1, 1, CodecsSavePageMode.Overwrite);

                            // マッチしたフォーマットに登録されているフィールド数を取得
                            int fieldNum = Format.NumOfFields;
                            int matchNum = Format.FormatNo + 1;
                            //////System.Console.WriteLine(matchNum + "番目のフォーマットがマッチ");
                            int i      = 1;
                            int fIndex = 0;
                            ocr_csv = "*,";

                            // ファイルに画像ファイル名フィールドを付加します
                            ocr_csv += System.IO.Path.GetFileName(files);

                            // 認識されたフィールドを順次読み出します
                            Field = Format.Begin();

                            // 3F伝票処理時に2F伝票を判定する 2013/07/01
                            if (FormatName == Properties.Settings.Default.instDir + Properties.Settings.Default.fmtHPath)
                            {
                                string fldText = string.Empty;
                                while (Field != null)
                                {
                                    // 指定フィールドを認識し、テキストを取得(対象は最終フィールド)
                                    fldText = Field.ExtractFieldText();

                                    // 次のフィールドの取得
                                    Field = Format.Next();
                                }

                                // 再度認識されたフィールドを順次読み出します 2013/07/01
                                Field = Format.Begin();

                                // 2F書式伝票のとき(指定フィールドが空白である)
                                if (fldText.Trim().Length == 0)
                                {
                                    // 2F伝票フォルダへ移動する
                                    System.IO.File.Move(files, path2Fdir + System.IO.Path.GetFileName(files));

                                    // ページをカウントして次の画像のOCR処理へ
                                    ocrPage++;
                                    nPage += 1;
                                    continue;
                                }
                            }

                            // 伝票フィールド編集
                            while (Field != null)
                            {
                                //カンマ付加
                                if (ocr_csv != string.Empty)
                                {
                                    ocr_csv += ",";
                                }

                                // 指定フィールドを認識し、テキストを取得
                                string strText = Field.ExtractFieldText();

                                // 年月日のとき各々独立フィールドに分解します
                                if (fIndex == 1)
                                {
                                    string strYYMMDD = strText.PadRight(6, '0');
                                    string ymd       = strYYMMDD.Substring(0, 2) + "," + strYYMMDD.Substring(2, 2) + "," + strYYMMDD.Substring(4, 2);
                                    ocr_csv += ymd;
                                }
                                else if (fIndex != 165)
                                {
                                    ocr_csv += strText;    // 他のフィールドで最終フィールド以外(2013/07/01)
                                }

                                // 摘要複写欄
                                if (fIndex == 10 || fIndex == 19 || fIndex == 28 || fIndex == 37 ||
                                    fIndex == 46 || fIndex == 55 || fIndex == 64 || fIndex == 73 || fIndex == 82 ||
                                    fIndex == 91 || fIndex == 100 || fIndex == 109 || fIndex == 118 || fIndex == 127 ||
                                    fIndex == 136 || fIndex == 145 || fIndex == 154 || fIndex == 163)
                                {
                                    ocr_csv += ",0";
                                }

                                // 改行
                                if (fIndex == 2 || fIndex == 11 || fIndex == 20 || fIndex == 29 || fIndex == 38 ||
                                    fIndex == 47 || fIndex == 56 || fIndex == 65 || fIndex == 74 || fIndex == 83 ||
                                    fIndex == 92 || fIndex == 101 || fIndex == 110 || fIndex == 119 || fIndex == 128 ||
                                    fIndex == 137 || fIndex == 146 || fIndex == 155)
                                {
                                    // ヘッダ業改行のとき明細行数を付加
                                    if (fIndex == 2)
                                    {
                                        ocr_csv += ",";
                                        ocr_csv += global.MAXGYOU_PRN.ToString();
                                    }

                                    ocr_csv += Environment.NewLine;

                                    // 取消欄
                                    ocr_csv += "0";
                                }

                                // 次のフィールドの取得
                                Field = Format.Next();
                                i    += 1;

                                // フィールドインデックスインクリメント
                                fIndex++;
                            }

                            //出力ファイル
                            System.IO.StreamWriter outFile = new System.IO.StreamWriter(InPath + System.IO.Path.GetFileNameWithoutExtension(files) + ".csv", false, System.Text.Encoding.GetEncoding(932));
                            outFile.WriteLine(ocr_csv);
                            outFile.Close();

                            //OCR変換枚数カウント
                            _okCount++;
                        }
                        catch (IDRWarning ex)
                        {
                            // Engine.MatchFormatRotate() で
                            // フォーマットにマッチしなかった場合、空ファイルを出力します
                            if (ex.No == ErrorCode.IDR_WARN_FORM_NO_MATCH)
                            {
                                //////// アンマッチフォルダへ移動する
                                //////System.IO.File.Move(files, NgPath + System.IO.Path.GetFileName(files));

                                // 区切り文字
                                ocr_csv = "*,";

                                // ファイルに画像ファイル名フィールドを付加します
                                ocr_csv += System.IO.Path.GetFileName(files);

                                // ヘッダ部 (決算仕訳区分、年、月、日、伝票№(NG))
                                ocr_csv += ",0,,,,NG," + global.MAXGYOU_PRN.ToString() + Environment.NewLine;

                                //// 明細部
                                string meisai = "0,,,,,,,,,0," + Environment.NewLine;
                                for (int i = 0; i < 18; i++)
                                {
                                    ocr_csv += meisai;
                                }

                                //出力ファイル
                                System.IO.StreamWriter outFile = new System.IO.StreamWriter(InPath + System.IO.Path.GetFileNameWithoutExtension(files) + ".csv", false, System.Text.Encoding.GetEncoding(932));
                                outFile.WriteLine(ocr_csv);
                                outFile.Close();

                                _ngCount++;  //NG枚数カウント
                            }
                        }

                        ocrPage++;
                        nPage += 1;
                    }
                }

                // いったんオーナーをアクティブにする
                this.Activate();

                // 進行状況ダイアログを閉じる
                frmP.Close();

                // オーナーのフォームを有効に戻す
                this.Enabled = true;

                // OCR変換画像とCSVデータをOCR結果出力フォルダへ移動する
                foreach (string files in System.IO.Directory.GetFiles(InPath, "*.*"))
                {
                    System.IO.File.Move(files, rePath + System.IO.Path.GetFileName(files));
                }

                // 終了メッセージ (2F伝票画像がなければ処理終了とみなす)
                var f2Tif = System.IO.Directory.GetFileSystemEntries(Properties.Settings.Default.instDir + global.DIR_2F, "*.tif");

                if (f2Tif.Length == 0)
                {
                    string        finMessage = string.Empty;
                    StringBuilder sb         = new StringBuilder();
                    sb.Append("OCR認識処理が終了しました。");
                    sb.Append("引き続き修正確認&受け渡しデータ作成を行ってください。");
                    sb.Append(Environment.NewLine);
                    sb.Append(Environment.NewLine);
                    sb.Append("OK件数 : ");
                    sb.Append(_okCount.ToString());
                    sb.Append(Environment.NewLine);
                    sb.Append("NG件数 : ");
                    sb.Append(_ngCount.ToString());
                    sb.Append(Environment.NewLine);

                    MessageBox.Show(sb.ToString(), "処理終了", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                FormatList.Delete(0);
            }
            catch (System.Exception ex)
            {
                // 例外のキャッチ
                string errMessage = string.Empty;
                errMessage += "System例外が発生しました:" + Environment.NewLine;
                errMessage += "必要なDLL等が実行モジュールと同ディレクトリに存在するか確認してください。:" + Environment.NewLine;
                errMessage += ex.Message.ToString();
                MessageBox.Show(errMessage, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            finally
            {
                en.Release();
            }
        }