C#使用Tesseract進(jìn)行中文識(shí)別的詳細(xì)步驟
1. 環(huán)境準(zhǔn)備與安裝
1.1 安裝 NuGet 包
在 Visual Studio 中,通過 NuGet 包管理器安裝 Tesseract:
1.2 配置語言數(shù)據(jù)文件
Tesseract 需要語言訓(xùn)練數(shù)據(jù)文件(.traineddata)才能識(shí)別特定語言的文字。對(duì)于中文識(shí)別,我們需要下載簡(jiǎn)體中文語言包:
下載語言包:
訪問 Tesseract OCR GitHub下載 chi_sim.traineddata(簡(jiǎn)體中文)
創(chuàng)建文件夾結(jié)構(gòu):
在項(xiàng)目根目錄創(chuàng)建 tessdata文件夾,并將下載的語言文件放入其中。
設(shè)置文件屬性:
右鍵點(diǎn)擊 chi_sim.traineddata文件
生成操作:設(shè)置為"內(nèi)容"
復(fù)制到輸出目錄:設(shè)置為"如果較新則復(fù)制" 或 “始終復(fù)制”
基本使用代碼
using System;
using Tesseract;
class Program
{
static void Main(string[] args)
{
// 圖片路徑
string imagePath = @"D:\test.png";
// tessdata 文件夾路徑
string tessDataPath = @".\tessdata";
try
{
// 初始化Tesseract引擎,使用簡(jiǎn)體中文
using (var engine = new TesseractEngine(tessDataPath, "chi_sim", EngineMode.Default))
{
// 加載圖片
using (var img = Pix.LoadFromFile(imagePath))
{
// 進(jìn)行OCR識(shí)別
using (var page = engine.Process(img))
{
// 獲取識(shí)別結(jié)果
string text = page.GetText();
// 獲取識(shí)別置信度
float confidence = page.GetMeanConfidence();
Console.WriteLine("識(shí)別結(jié)果:");
Console.WriteLine("-----------------------------------");
Console.WriteLine(text);
Console.WriteLine("-----------------------------------");
Console.WriteLine($"識(shí)別置信度: {confidence:P}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"識(shí)別出錯(cuò): {ex.Message}");
}
}
}
2.核心API詳解
2.1引擎模式對(duì)比表
page.GetMeanConfidence()- 置信度獲取
GetMeanConfidence()方法返回OCR識(shí)別的置信度,數(shù)值范圍在0.0到1.0之間,表示識(shí)別結(jié)果的可靠程度。

2.2引擎模式對(duì)比表

3. 高級(jí)功能與優(yōu)化
public Pix PreprocessImage(string imagePath)
{
// 加載原始圖片
using (var original = Pix.LoadFromFile(imagePath))
{
// 1. 轉(zhuǎn)為灰度圖
using (var gray = original.ConvertRGBToGray())
{
// 2. 調(diào)整對(duì)比度
using (var contrast = gray.AdjustContrast(1.5f))
{
// 3. 二值化(黑白化)
using (var binary = contrast.BinarizeOtsuAdaptiveThreshold())
{
// 4. 降噪
using (var denoised = binary.RemoveNoise())
{
// 5. 銳化
using (var sharpened = denoised.UnsharpMasking(1.5f, 0.7f))
{
return sharpened.Clone();
}
}
}
}
}
}
}
3.1頁面分割模式(Page Segmentation Mode)
// 設(shè)置不同的頁面分割模式
public void SetPageSegmentationModes(TesseractEngine engine)
{
// 模式0: 方向檢測(cè)和腳本檢測(cè)
engine.SetVariable("tessedit_pageseg_mode", "0");
// 模式1: 自動(dòng)頁面分割,啟用方向檢測(cè)
engine.SetVariable("tessedit_pageseg_mode", "1");
// 模式2: 自動(dòng)頁面分割,不啟用方向檢測(cè)
engine.SetVariable("tessedit_pageseg_mode", "2");
// 模式3: 全自動(dòng)頁面分割(默認(rèn))
engine.SetVariable("tessedit_pageseg_mode", "3");
// 模式4: 假設(shè)單列可變大小的文本
engine.SetVariable("tessedit_pageseg_mode", "4");
// 模式5: 假設(shè)統(tǒng)一的垂直對(duì)齊文本塊
engine.SetVariable("tessedit_pageseg_mode", "5");
// 模式6: 假設(shè)統(tǒng)一的文本塊
engine.SetVariable("tessedit_pageseg_mode", "6");
// 模式7: 將圖像視為單個(gè)文本行
engine.SetVariable("tessedit_pageseg_mode", "7");
// 模式8: 將圖像視為單個(gè)單詞
engine.SetVariable("tessedit_pageseg_mode", "8");
// 模式9: 將圖像視為圓形中的單個(gè)單詞
engine.SetVariable("tessedit_pageseg_mode", "9");
// 模式10: 將圖像視為單個(gè)字符
engine.SetVariable("tessedit_pageseg_mode", "10");
}
3.2識(shí)別特定區(qū)域(ROI)
public string RecognizeRegion(string imagePath, Rect region)
{
using (var engine = new TesseractEngine(tessDataPath, "chi_sim", EngineMode.Default))
{
using (var img = Pix.LoadFromFile(imagePath))
{
// 設(shè)置識(shí)別區(qū)域
using (var page = engine.Process(img, region))
{
return page.GetText();
}
}
}
}
// 使用示例
Rect region = new Rect(100, 100, 300, 200); // x, y, width, height
string result = RecognizeRegion(@"D:\test.png", region);
4.智能OCR識(shí)別類
using System;
using System.Collections.Generic;
using System.IO;
using Tesseract;
namespace TesseractOCRHelper
{
public class SmartOCR
{
private readonly string _tessDataPath;
public SmartOCR(string tessDataPath = null)
{
_tessDataPath = tessDataPath ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tessdata");
if (!Directory.Exists(_tessDataPath))
{
throw new DirectoryNotFoundException($"tessdata目錄不存在: {_tessDataPath}");
}
}
/// <summary>
/// 識(shí)別圖片中的文字
/// </summary>
public OcrResult Recognize(string imagePath, string language = "chi_sim",
EngineMode? engineMode = null, Rect? region = null)
{
if (!File.Exists(imagePath))
{
return new OcrResult
{
Success = false,
ErrorMessage = $"圖片文件不存在: {imagePath}"
};
}
try
{
var mode = engineMode ?? EngineMode.Default;
using (var engine = new TesseractEngine(_tessDataPath, language, mode))
{
// 優(yōu)化識(shí)別參數(shù)
ConfigureEngine(engine);
using (var img = Pix.LoadFromFile(imagePath))
{
Page page;
if (region.HasValue)
{
page = engine.Process(img, region.Value);
}
else
{
page = engine.Process(img);
}
using (page)
{
return new OcrResult
{
Success = true,
Text = page.GetText(),
Confidence = page.GetMeanConfidence(),
EngineMode = mode.ToString(),
Language = language
};
}
}
}
}
catch (Exception ex)
{
return new OcrResult
{
Success = false,
ErrorMessage = $"OCR識(shí)別失敗: {ex.Message}"
};
}
}
/// <summary>
/// 智能識(shí)別:自動(dòng)選擇最佳引擎
/// </summary>
public OcrResult SmartRecognize(string imagePath, float confidenceThreshold = 0.7f)
{
// 先用默認(rèn)模式
var result = Recognize(imagePath, "chi_sim", EngineMode.Default);
// 如果置信度低于閾值,嘗試LSTM模式
if (result.Success && result.Confidence < confidenceThreshold)
{
Console.WriteLine($"默認(rèn)模式置信度較低({result.Confidence:P}),嘗試LSTM模式...");
var lstmResult = Recognize(imagePath, "chi_sim", EngineMode.LstmOnly);
if (lstmResult.Success && lstmResult.Confidence > result.Confidence)
{
lstmResult.Message = $"從默認(rèn)模式切換到LSTM模式,置信度提升: {result.Confidence:P} -> {lstmResult.Confidence:P}";
return lstmResult;
}
}
return result;
}
/// <summary>
/// 批量識(shí)別
/// </summary>
public List<OcrResult> BatchRecognize(List<string> imagePaths, string language = "chi_sim")
{
var results = new List<OcrResult>();
foreach (var imagePath in imagePaths)
{
Console.WriteLine($"正在處理: {Path.GetFileName(imagePath)}");
var result = Recognize(imagePath, language);
results.Add(result);
}
return results;
}
/// <summary>
/// 配置引擎參數(shù)
/// </summary>
private void ConfigureEngine(TesseractEngine engine)
{
// 設(shè)置頁面分割模式
engine.SetVariable("tessedit_pageseg_mode", "3"); // 全自動(dòng)
// 設(shè)置白名單(可選)
// engine.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
// 設(shè)置黑名單(可選)
// engine.SetVariable("tessedit_char_blacklist", "!@#$%^&*()");
// 設(shè)置OCR引擎模式
engine.SetVariable("classify_bln_numeric_mode", "0");
}
/// <summary>
/// 預(yù)處理圖片
/// </summary>
public Pix PreprocessImage(string imagePath)
{
using (var original = Pix.LoadFromFile(imagePath))
{
// 1. 轉(zhuǎn)為灰度
using (var gray = original.ConvertRGBToGray())
{
// 2. 二值化
using (var binary = gray.BinarizeOtsuAdaptiveThreshold())
{
// 3. 降噪
using (var denoised = binary.RemoveNoise())
{
return denoised.Clone();
}
}
}
}
}
}
/// <summary>
/// OCR識(shí)別結(jié)果
/// </summary>
public class OcrResult
{
public bool Success { get; set; }
public string Text { get; set; }
public float Confidence { get; set; }
public string EngineMode { get; set; }
public string Language { get; set; }
public string Message { get; set; }
public string ErrorMessage { get; set; }
public override string ToString()
{
if (!Success)
{
return $"識(shí)別失敗: {ErrorMessage}";
}
return $"識(shí)別成功! 模式: {EngineMode}, 語言: {Language}, 置信度: {Confidence:P}\n" +
$"識(shí)別結(jié)果:\n{Text}\n" +
$"{(string.IsNullOrEmpty(Message) ? "" : $"備注: {Message}")}";
}
}
}
到此這篇關(guān)于C#使用Tesseract進(jìn)行中文識(shí)別的全過程的文章就介紹到這了,更多相關(guān)C# Tesseract中文識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c# volatile 關(guān)鍵字的拾遺補(bǔ)漏
這篇文章主要介紹了c# volatile 關(guān)鍵字的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)c#的相關(guān)知識(shí),感興趣的朋友可以了解下2020-10-10
C#身份證識(shí)別相關(guān)技術(shù)功能詳解
這篇文章主要介紹了C#身份證識(shí)別相關(guān)技術(shù)詳解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
c#高效率導(dǎo)出多維表頭excel的實(shí)例代碼
這篇文章介紹了c#高效率導(dǎo)出多維表頭excel的實(shí)例代碼,有需要的朋友可以參考一下2013-11-11
C#實(shí)現(xiàn)定義一套中間SQL可以跨庫執(zhí)行的SQL語句(案例詳解)
這篇文章主要介紹了C#實(shí)現(xiàn)定義一套中間SQL可以跨庫執(zhí)行的SQL語句,主要包括hisql查詢樣例、group by查詢、鏈?zhǔn)讲樵兗癶isql語句和鏈?zhǔn)讲樵兓煊玫膕ql語句,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07
C# 全角和半角轉(zhuǎn)換以及判斷的簡(jiǎn)單代碼
這篇文章介紹了在C#中判斷和轉(zhuǎn)換全角半角的方法,有需要的朋友可以參考一下2013-07-07
C#實(shí)現(xiàn)動(dòng)態(tài)生成表格的方法
這篇文章主要介紹了C#實(shí)現(xiàn)動(dòng)態(tài)生成表格的方法,是C#程序設(shè)計(jì)中非常實(shí)用的技巧,需要的朋友可以參考下2014-09-09

