[英]tesseract multithreading c#
I have a code for tesseract to run in 1 instance how can i parallelize the code so that it can run in quad core processor or 8 core processor systems.here is my code block.thanks in advance.我有一个 tesseract 的代码可以在 1 个实例中运行我如何并行化代码以便它可以在四核处理器或 8 核处理器系统中运行。这是我的代码块。提前致谢。
using (TesseractEngine engine = new TesseractEngine(@"./tessdata", "tel+tel1", EngineMode.Default))
{
foreach (string ab in files)
{
using (var pages = Pix.LoadFromFile(ab))
{
using (Tesseract.Page page = engine.Process(pages,Tesseract.PageSegMode.SingleBlock))
{
string text = page.GetText();
OCRedText.Append(text);
}
}
}
The most simple way to run this code in parallel is using PLINQ . 并行运行此代码的最简单方法是使用PLINQ 。 Calling AsParallel() on enumeration will automatically run query that follows it ( .Select(...) ) simultaneously on all available CPU cores.
在枚举上调用AsParallel()将自动在所有可用CPU内核上同时运行紧随其后的查询( .Select(...) )。
It is crucial to run in parallel only thread-safe code. 仅并行运行线程安全代码至关重要。 Assuming TesseractEngine is thread-safe (as you suggest in comment, I didn't verify it myself) as well as Pix.LoadFromFile(), then the only problematic part could be OCRedText.Append() .
假设TesseractEngine和Pix.LoadFromFile()是线程安全的(正如您在评论中建议的那样,我自己没有对其进行验证),则唯一有问题的部分可能是OCRedText.Append() 。 It is not clear from code, what OCRedText is, so I assume it is StringBuilder or List and therefore it is not thread-safe.
从代码尚不清楚OCRedText是什么,因此我假设它是StringBuilder或List,因此它不是线程安全的。 So I removed this part from code that will run in parallel and I process it later in single-thread - since method .Append() is likely to run fast, this shouldn't have significant adverse effect on overall performance.
因此,我从将要并行运行的代码中删除了这部分,然后稍后在单线程中对其进行处理-由于方法.Append()可能运行速度很快,因此这不会对整体性能产生重大不利影响。
using (TesseractEngine engine = new TesseractEngine(@"./tessdata", "tel+tel1", EngineMode.Default))
{
var texts = files.AsParallel().Select(ab =>
{
using (var pages = Pix.LoadFromFile(ab))
{
using (Tesseract.Page page = engine.Process(pages, eract.PageSegMode.SingleBlock))
{
return page.GetText();
}
}
});
foreach (string text in texts)
{
OCRedText.Append(text);
}
}
This has worked for me:这对我有用:
static IEnumerable<string> Ocr(string directory, string sep)
=> Directory.GetFiles(directory, sep)
.AsParallel()
.Select(x =>
{
using var engine = new TesseractEngine(@"D:\source\repos\WPF\OcrTest\tessdata\", "deu", EngineMode.Default);
using var img = Pix.LoadFromFile(x);
using var page = engine.Process(img);
return page.GetText();
}).ToList();
I am no expert on the matter of parallelization, but this function ocr's 8 Tiff's in 12 seconds.我不是并行化问题的专家,但是这个 function ocr 在 12 秒内完成了 8 个 Tiff。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.