Tesseract-OCR命令及WPF简单使用

Tesseract 是一个开源的 OCR 引擎,可以识别多种格式的图像文件并将其转换成文本,最初由 HP 公司开发,后来由 Google 维护。
下载地址:https://digi.bib.uni-mannheim.de/tesseract/
在这里插入图片描述
其中文件名中带有 dev 的为开发版本,不带 dev 的为稳定版本。
安装时可以添加支持的语言包,如下界面最后一个选项点开选择,我们可以选择简体中文 Chiness(Simplified)。
在这里插入图片描述
添加中文的识别库:

https://github.com/tesseract-ocr/tessdata/find/master

这个网址中下载chi_sim.traineddata,下载后放到Tesseract-OCR\tessdata文件夹内。

设置环境变量:
安装完成后在Windows下把tesseract.exe所在的路径添加到PATH环境变量中。

另外一个环境变量我自己电脑中是没有添加,也可以正常运行程序。做个参考:


在使用tesseract命令行进行测试时,报以下的错误

Error opening data file \Program Files (x86)\Tesseract-OCR\tessdata/eng.traineddata
Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory.
Failed loading language 'eng'
Tesseract couldn't load any languages!
Could not initialize tesseract.

报错是意思是缺少环境变量TESSDATA_PREFIX,导致无法加载任何语言,就不能初始化tesseract。

解决的方法也很简单,在环境变量中,添加一个变量名为TESSDATA_PREFIX,变量值为teseractdata目录地址。


在命令行中使用tesseract识别图像:
如果想要在cmd下能够使用tesseract命令,那么需要把tesseract.exe所在的目录放到PATH环境变量中。然后使用命令:tesseract 图片路径 文件路径。
示例:

tesseract a.png a

那么就会识别出a.png中的图片,并且把文字写入到a.txt中。

如果识别中文的,需要添加个参数:

tesseract a.png a -l eng 默认的是eng,中文的就改成chi_sim。

关于快速的在当前文件夹内打开cmd的方法,是按住shift键,然后右键,就可以有“在此处打开命令行窗口”的选项,并且直接定位到当前文件夹内。


#region 图片转文字 ocr

private static string CmdPath = @"C:\Windows\System32\cmd.exe";

/// <summary>
/// 执行cmd命令
/// 多命令请使用批处理命令连接符:
/// <![CDATA[
/// &:同时执行两个命令
/// |:将上一个命令的输出,作为下一个命令的输入
/// &&:当&&前的命令成功时,才执行&&后的命令
/// ||:当||前的命令失败时,才执行||后的命令]]>
/// 其他请百度
/// </summary>
/// <param name="cmd"></param>
/// <param name="output"></param>
public  void RunCmd(string cmd, out string output)
{
    
    
    cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
    Console.WriteLine(cmd);
    using (Process p = new Process())
    {
    
    
        p.StartInfo.FileName = CmdPath;

        p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动

        p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息

        p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息

        p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出

        p.StartInfo.CreateNoWindow = true;          //不显示程序窗口

        p.Start();//启动程序

        //向cmd窗口写入命令
        p.StandardInput.WriteLine(cmd);

        p.StandardInput.AutoFlush = true;

        p.StandardInput.Close();
        //获取cmd窗口的输出信息
        output = p.StandardError.ReadToEnd();

        p.WaitForExit();//等待程序执行完退出进程

        p.Close();

    }

}
public string ImageToText(string imgPath)
{
    
    
    try
    {
    
    
        //Thread.Sleep(3000);

        //using (var engine = new TesseractEngine("tessdata", "eng", EngineMode.Default))
        //{
    
    
        //    using (var img = Pix.LoadFromFile(imgPath))
        //    {
    
    
        //        using (var page = engine.Process(img))
        //        {
    
    
        //            return page.GetText();
        //        }
        //    }
        //}
        string saveDir = string.Format(@"{0}Images\{1}\", this.GetBaseDirectory(), DateTime.Now.ToString("yyyy-MM-dd"));

        if (!System.IO.Directory.Exists(saveDir))
        {
    
    
            System.IO.Directory.CreateDirectory(saveDir);
        }
        string txtPath = saveDir + string.Format(@"{0}_{1}", ViewModel.TestInfo.Barcode, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));

        string cmd = "tesseract " + imgPath + " " + txtPath;
        
        string iii = "";
        
        RunCmd(cmd,out iii);
      
        Thread.Sleep(1000);

        string txtfile = txtPath + ".txt" ;

        if(File.Exists(txtfile))
        {
    
    
            string text = File.ReadAllText(txtfile);

            return text;
        }
        else
        {
    
    
            return null;
        }

    } catch (Exception ex){
    
    

        System.Windows.MessageBox.Show("OCR解析失败:" + ex.Message);
        return null;
    }
}
#endregion

猜你喜欢

转载自blog.csdn.net/BeanGo/article/details/129194369