Como extrair texto de um arquivo de imagem

Como usar o Iron Tesseract em C

This article was translated from English: Does it need improvement?
Translated
View the article in English

O Iron Tesseract em C# é usado criando uma instância IronTesseract, configurando-a com configuração de linguagem e OCR, em seguida, chamando o método Read() em um objeto OcrInput contendo suas imagens ou PDFs. Isso converte imagens de texto em PDFs pesquisáveis usando o motor otimizado da Tesseract 5.

O IronOCR fornece uma API intuitiva para utilizar o Tesseract 5 personalizado e otimizado, conhecido como Iron Tesseract. Usando o IronOCR e IronTesseract, você será capaz de converter imagens de texto e documentos digitalizados em texto e PDFs pesquisáveis. A biblioteca oferece suporte a 125 idiomas internacionais e inclui recursos avançados como leitura de código de barras e visão computacional .

Início rápido: Configurar o IronTesseract em C#

Este exemplo demonstra como configurar IronTesseract com configurações específicas e executar OCR em uma única linha de código.

  1. Instale IronOCR com o Gerenciador de Pacotes NuGet

    PM > Install-Package IronOcr
  2. Copie e execute este trecho de código.

    var result = new IronOcr.IronTesseract { Language = IronOcr.OcrLanguage.English, Configuration = new IronOcr.TesseractConfiguration { ReadBarCodes = false, RenderSearchablePdf = true, WhiteListCharacters = "ABCabc123" } }.Read(new IronOcr.OcrInput("image.png"));
  3. Implante para testar em seu ambiente de produção.

    Comece a usar IronOCR em seu projeto hoje com uma avaliação gratuita

    arrow pointer

Como faço para criar uma instância do IronTesseract?

Inicialize um objeto Tesseract com este código:

:path=/static-assets/ocr/content-code-examples/how-to/irontesseract-initialize-irontesseract.cs
using IronOcr;

IronTesseract ocr = new IronTesseract();
Imports IronOcr

Dim ocr As New IronTesseract()
$vbLabelText   $csharpLabel

Você pode personalizar o comportamento de IronTesseract selecionando diferentes idiomas, habilitando leitura de código de barras e listando/branqueando caracteres. O IronOCR oferece opções de configuração abrangentes para ajustar seu processo de OCR:

:path=/static-assets/ocr/content-code-examples/how-to/irontesseract-configure-irontesseract.cs
IronTesseract ocr = new IronTesseract
{
    Configuration = new TesseractConfiguration
    {
        ReadBarCodes = false,
        RenderHocr = true,
        TesseractVariables = null,
        WhiteListCharacters = null,
        BlackListCharacters = "`ë|^",
    },
    MultiThreaded = false,
    Language = OcrLanguage.English,
    EnableTesseractConsoleMessages = true, // False as default
};
Dim ocr As New IronTesseract With {
	.Configuration = New TesseractConfiguration With {
		.ReadBarCodes = False,
		.RenderHocr = True,
		.TesseractVariables = Nothing,
		.WhiteListCharacters = Nothing,
		.BlackListCharacters = "`ë|^"
	},
	.MultiThreaded = False,
	.Language = OcrLanguage.English,
	.EnableTesseractConsoleMessages = True
}
$vbLabelText   $csharpLabel

Uma vez configurado, você pode usar a funcionalidade Tesseract para ler objetos OcrInput. A classe OcrInput fornece métodos flexíveis para carregar diversos formatos de entrada:

:path=/static-assets/ocr/content-code-examples/how-to/irontesseract-read.cs
IronTesseract ocr = new IronTesseract();

using OcrInput input = new OcrInput();
input.LoadImage("attachment.png");
OcrResult result = ocr.Read(input);
string text = result.Text;
Dim ocr As New IronTesseract()

Using input As New OcrInput()
	input.LoadImage("attachment.png")
	Dim result As OcrResult = ocr.Read(input)
	Dim text As String = result.Text
End Using
$vbLabelText   $csharpLabel

Para cenários complexos, você pode aproveitar os recursos de multithreading para processar vários documentos simultaneamente, melhorando significativamente o desempenho das operações em lote.

Quais são as variáveis ​​de configuração avançadas do Tesseract?

A interface IronOcr Tesseract permite o controle total das variáveis ​​de configuração do Tesseract através da classe IronOcr.TesseractConfiguration . Essas configurações avançadas permitem otimizar o desempenho do OCR para casos de uso específicos, como corrigir digitalizações de baixa qualidade ou ler tipos específicos de documentos .

Como faço para usar a configuração do Tesseract no código?

:path=/static-assets/ocr/content-code-examples/how-to/irontesseract-tesseract-configuration.cs
using IronOcr;
using System;

IronTesseract Ocr = new IronTesseract();

Ocr.Language = OcrLanguage.English;
Ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd;

// Configure Tesseract Engine
Ocr.Configuration.TesseractVariables["tessedit_parallelize"] = false;

using var input = new OcrInput();
input.LoadImage("/path/file.png");

OcrResult Result = Ocr.Read(input);
Console.WriteLine(Result.Text);
Imports IronOcr
Imports System

Private Ocr As New IronTesseract()

Ocr.Language = OcrLanguage.English
Ocr.Configuration.PageSegmentationMode = TesseractPageSegmentationMode.AutoOsd

' Configure Tesseract Engine
Ocr.Configuration.TesseractVariables("tessedit_parallelize") = False

Dim input = New OcrInput()
input.LoadImage("/path/file.png")

Dim Result As OcrResult = Ocr.Read(input)
Console.WriteLine(Result.Text)
$vbLabelText   $csharpLabel

O IronOCR também oferece configurações especializadas para diferentes tipos de documentos. Por exemplo, ao ler passaportes ou processar cheques MICR , você pode aplicar filtros de pré-processamento específicos e detecção de região para melhorar a precisão.

Exemplo de configuração para documentos financeiros:

:path=/static-assets/ocr/content-code-examples/how-to/iron-tesseract-6.cs
// Example: Configure for financial documents
IronTesseract ocr = new IronTesseract
{
    Language = OcrLanguage.English,
    Configuration = new TesseractConfiguration
    {
        PageSegmentationMode = TesseractPageSegmentationMode.SingleBlock,
        TesseractVariables = new Dictionary<string, object>
        {
            ["tessedit_char_whitelist"] = "0123456789.$,",
            ["textord_heavy_nr"] = false,
            ["edges_max_children_per_outline"] = 10
        }
    }
};

// Apply preprocessing filters for better accuracy
using OcrInput input = new OcrInput();
input.LoadPdf("financial-document.pdf");
input.Deskew();
input.EnhanceResolution(300);

OcrResult result = ocr.Read(input);
Imports IronOcr

' Example: Configure for financial documents
Dim ocr As New IronTesseract With {
    .Language = OcrLanguage.English,
    .Configuration = New TesseractConfiguration With {
        .PageSegmentationMode = TesseractPageSegmentationMode.SingleBlock,
        .TesseractVariables = New Dictionary(Of String, Object) From {
            {"tessedit_char_whitelist", "0123456789.$,"},
            {"textord_heavy_nr", False},
            {"edges_max_children_per_outline", 10}
        }
    }
}

' Apply preprocessing filters for better accuracy
Using input As New OcrInput()
    input.LoadPdf("financial-document.pdf")
    input.Deskew()
    input.EnhanceResolution(300)

    Dim result As OcrResult = ocr.Read(input)
End Using
$vbLabelText   $csharpLabel

Qual é a lista completa de todas as variáveis ​​de configuração do Tesseract?

Estas podem ser configuradas usando IronTesseract.Configuration.TesseractVariables["key"] = value;. As variáveis ​​de configuração permitem ajustar o comportamento do OCR para obter resultados ideais com seus documentos específicos. Para obter orientações detalhadas sobre como otimizar o desempenho do OCR, consulte nosso guia de configuração rápida de OCR .

Variável de configuração do Tesseract Default Significado
classificar_num_níveis_cp3Número de níveis do podador de classe
textord_debug_tabfind0Encontrando a guia Depurar
textord_debug_bugs0Ative a saída relacionada a erros na localização de guias.
textord_testregion_esquerda-1Borda esquerda do retângulo de relatório de depuração
textord_testregion_top-1Borda superior do retângulo de relatório de depuração
textord_testregion_right2147483647Borda direita do retângulo de depuração
textord_testregion_bottom2147483647Borda inferior do retângulo de depuração
textord_tabfind_mostrar_partições0Exibir limites da partição, aguardando se >1
devanagari_split_debuglevel0Nível de depuração para o processo shiro-rekha dividido.
bordas_máximo_filhos_por_contorno10Número máximo de crianças dentro do contorno de um personagem.
camadas_filhas_máximas_de_bordas5Número máximo de camadas de filhos aninhados dentro do contorno de um personagem.
bordas_filhos_por_neto10Proporção de importância para contornos de recorte
limite_de_contagem_de_filhos_das_bordas45Número máximo de buracos permitidos na bolha
bordas_mín_sem_buraco12Número mínimo de pixels para possível caractere na caixa
proporção_área_do_caminho_das_bordas40Max lensq/area for acceptable child outline
textord_fp_chop_error2Max permitiu a flexão das células picadas
textord_tabfind_mostrar_imagens0Show image blobs
textord_skewsmooth_offset4Para fator suave
textord_skewsmooth_offset21Para fator suave
textord_test_x-2147483647coordenadas do ponto de teste
textord_test_y-2147483647coordenadas do ponto de teste
textord_min_blobs_in_row4Número mínimo de blobs antes da contagem do gradiente
textord_spline_minblobs8Min blobs in each spline segment
textord_spline_medianwin6Size of window for spline segmentation
textord_max_blob_overlaps4Max number of blobs a big blob can overlap
textord_min_xheight10Min credible pixel xheight
textord_lms_line_trials12Number of linew fits to do
oldbl_holed_losscount10Max lost before fallback line used
versão_linear_pitsync6Use new fast algorithm
pitsync_profundidade_falsa1Max advance fake generation
textord_tabfind_show_strokewidths0Show stroke widths
textord_dotmatrix_gap3Max pixel gap for broken pixed pitch
bloco de depuração textord0Block to do debug on
textord_pitch_range2Max range test on pitch
textord_words_veto_power5Rows required to outvote a veto
equationdetect_save_bi_image0Save input bi image
equationdetect_save_spt_image0Save special character image
equationdetect_save_semente_imagem0Save the seed image
equationdetect_save_merged_image0Save the merged image
poly_debug0Debug old poly
poly_wide_objects_better1More accurate approx on wide things
wordrec_display_splits0Display splits
textord_debug_printable0Make debug windows printable
tamanho_do_espaço_textord_é_variável0If true, word delimiter spaces are assumed to have variable width, even though characters have fixed pitch.
textord_tabfind_show_initial_partitions0Show partition bounds
textord_tabfind_show_reject_blobs0Show blobs rejected as noise
textord_tabfind_show_columns0Show column bounds
textord_tabfind_show_blocks0Show final block bounds
textord_tabfind_find_tables1run table detection
devanagari_split_debugimage0Whether to create a debug image for split shiro-rekha process.
textord_mostrar_cortes_fixos0Draw fixed pitch cell boundaries
edges_use_new_outline_complexity0Use the new outline complexity module
bordas_depuração0turn on debugging for this module
correção de bordas_filhos0Remove boxy parents of char-like children
gapmap_debug0Say which blocks have tables
gapmap_use_ends0Use large space at start and end of rows
gapmap_sem_quanta_isolada0Ensure gaps not less than 2quanta wide
textord_pesado_nr0Vigorously remove noise
textord_mostrar_linhas_iniciais0Display row accumulation
textord_mostrar_linhas_paralelas0Display page correlated rows
textord_mostrar_linhas_expandidas0Display rows after expanding
textord_mostrar_linhas_finais0Display rows after final fitting
textord_mostrar_blobs_finais0Display blob bounds after pre-ass
textord_test_landscape0Tests refer to land/port
textord_linhas_de_base_paralelas1Force parallel baselines
textord_linhas_de_base_retas0Force straight baselines
textord_old_baselines1Use old baseline algorithm
textord_old_xheight0Use old xheight algorithm
textord_fix_xheight_bug1Use spline baseline
textord_fix_makerow_bug1Prevent multiple baselines
textord_debug_xheights0Test xheight algorithms
textord_biased_skewcalc1Bias skew estimates with line length
textord_interpolating_skew1Interpolate across gaps
textord_new_inicial_xheight1Use test xheight mechanism
textord_debug_blob0Print test blob information
textord_realmente_antigo_xheight0Use original wiseowl xheight
textord_oldbl_debug0Debug old baseline generation
textord_debug_baselines0Debug baseline generation
textord_oldbl_paradef1Use para default mechanism
textord_oldbl_split_splines1Split stepped splines
textord_oldbl_merge_parts1Merge suspect partitions
correção antigabl1Improve correlation of heights
oldbl_xhfix0Fix bug in modes threshold for xheights
textord_ocropus_mode0Make baselines for ocropus
textord_tabfind_only_strokewidths0Only run stroke widths
textord_tabfind_show_initialtabs0Show tab candidates
textord_tabfind_show_finaltabs0Show tab vectors
textord_mostrar_tabelas0Show table regions
textord_tablefind_show_mark0Debug table marking steps in detail
textord_tablefind_show_stats0Show page stats used in table finding
textord_tablefind_recognize_tables0Enables the table recognizer for table layout and filtering.
textord_all_prop0All doc is proportial text
textord_debug_pitch_test0Debug on fixed pitch test
textord_disable_pitch_test0Turn off dp fixed pitch algorithm
textord_fast_pitch_test0Do even faster pitch algorithm
textord_debug_pitch_metric0Write full metric stuff
textord_show_row_cuts0Draw row-level cuts
textord_mostrar_recortes_de_página0Draw page-level cuts
textord_pitch_cheat0Use correct answer for fixed/prop
textord_blockndoc_fixado0Attempt whole doc/block fixed pitch
textord_mostrar_palavras_iniciais0Display separate words
textord_mostrar_novas_palavras0Display separate words
textord_mostrar_palavras_fixas0Display forced fixed pitch words
textord_blocksall_fixed0Moan about prop blocks
textord_blocksall_prop0Moan about fixed pitch blocks
textord_blocksall_testing0Dump stats when moaning
textord_modo_teste0Do current test
similaridade_linha_textord_pitch0.08Fraction of xheight for sameness
palavras_iniciais_minúsculas0.5Max initial cluster size
palavras_iniciais_maiúsculas0.15Min initial cluster spacing
palavras_propriedade_padrão_não_espaço0.25Fraction of xheight
palavras_padrão_espaço_fixo0.75Fraction of xheight
palavras_padrão_limite_fixo0.6Allowed size variance
textord_words_definite_spread0.3Non-fuzzy spacing region
textord_spacesize_ratiofp2.8Min ratio space/nonspace
textord_spacesize_ratioprop2Min ratio space/nonspace
textord_fpiqr_ratio1.5Pitch IQR/Gap IQR threshold
textord_max_pitch_iqr0.2Xh fraction noise in pitch
textord_fp_min_width0.5Min width of decent blobs
textord_underline_offset0.1Fraction of x to ignore
nível_de_depuração_ambigs0Debug level for unichar ambiguities
nível_de_depuração_classificar0Classify debug level
método_de_normação_classificatória1Normalization Method ...
matcher_debug_level0Matcher Debug Level
sinalizadores_de_depuração_do_correspondente0Matcher Debug Flags
nível de depuração de aprendizado de classificação0Learning Debug Level:
matcher_permanent_classes_min1Min # of permanent classes
matcher_min_examples_for_prototyping3Reliable Config Threshold
matcher_sufficient_examples_for_prototyping5Enable adaption even if the ambiguities have not been seen
limiar_de_adaptação_proto230Threshold for good protos during adaptive 0-255
limiar de adaptação de classificação230Threshold for good features during adaptive 0-255
limiar_classify_class_prunter229Class Pruner Threshold 0-255
multiplicador_de_podador_de_classificação15Class Pruner Multiplier 0-255:
classificar_cp_força_de_corte7Class Pruner CutoffStrength:
classificar_multiplicador_de_correspondência_inteira10Integer Matcher Multiplier 0-255:
nível de depuração dawg0Set to 1 for general debug info, to 2 for more details, to 3 to see all the debug messages
nível_de_depuração_hífen0Debug level for hyphenated words.
stopper_smallword_size2Size of dict word to be treated as non-dict word
nível_de_depuração_stopper0Stopper debug level
tessedit_truncate_wordchoice_log10Max words to keep in list
tentativas_máximas_permutador10000Maximum number of different character choices to consider during permutation. This limit is especially useful when user patterns are specified, since overly generic patterns can result in dawg search exploring an overly large number of options.
reparar_blobs_não_cortados1Fix blobs that aren't chopped
chop_debug0Chop debug
comprimento_dividido_cortado10000Split Length
cortar_mesma_distância2Same distance
pontos_mínimos_de_contorno6Min Number of Points on Outline
tamanho_da_pilha_da_costura_picada150Max number of seams in seam_pile
ângulo_interno_cortado-50Min Inside Angle Bend
área de contorno mínima de corte2000Min Outline Area
largura_máxima_centralizada_cortada90Width of (smaller) chopped blobs above which we don't care that a chop is not near the center.
peso_cortado_x_y3X / Y length weight
nível_de_depuração_wordrec0Debug level for wordrec
wordrec_max_join_chunks4Max number of broken pieces to associate
nível_de_depuração_da_busca_segmentada0SegSearch debug level
segsearch_max_pain_points2000Maximum number of pain points stored in the queue
segsearch_max_futile_classifications20Maximum number of pain point classifications per chunk that did not result in finding a better word choice.
nível de depuração do modelo de linguagem0Language model debug level
ordem_ngram_modelo_de_linguagem8Maximum order of the character ngram model
language_model_viterbi_list_ max_num_prunable10Maximum number of prunable (those for which PrunablePath() is true) entries in each viterbi list recorded in BLOB_CHOICEs
language_model_viterbi_list_max_size500Maximum size of viterbi lists recorded in BLOB_CHOICEs
comprimento_mínimo_composto_do_modelo_de_linguagem3Minimum length of compound words
wordrec_display_segmentations0Display Segmentations
tessedit_pageseg_mode6Page seg mode: 0=osd only, 1=auto+osd, 2=auto_only, 3=auto, 4=column, 5=block_vert, 6=block, 7=line, 8=word, 9=word_circle, 10=char,11=sparse_text, 12=sparse_text+osd, 13=raw_line (Values from PageSegMode enum in tesseract/publictypes.h)
tessedit_ocr_engine_mode2Which OCR engine(s) to run (Tesseract, LSTM, both). Defaults to loading and running the most accurate available.
páginaseg_devanagari_split_strategy0Whether to use the top-line splitting process for Devanagari documents while performing page-segmentation.
ocr_devanagari_split_strategy0Whether to use the top-line splitting process for Devanagari documents while performing ocr.
bidi_debug0Debug level for BiDi
applybox_debug1Debug level
applybox_page0Page number to apply boxes from
tessedit_bigram_debug0Amount of debug output for bigram correction.
remoção de ruído de depuração0Debug reassignment of small outlines
ruído_máximoporblob8Max diacritics to apply to a blob
ruído_máximo_por_palavra16Max diacritics to apply to a word
debug_x_ht_level0Reestimate debug
qualidade_mínima_inicial_alfas_reqd2alphas in a good word
tessedit_tess_adaption_mode39Adaptation decision algorithm for tess
nível de depuração multilíngue0Print multilang debug info.
nível_de_depuração_de_parágrafo0Print paragraph debug info.
tessedit_preserve_min_wd_len2Only preserve wds longer than this
classificação_máxima_de_crucagem10For adj length in rating per ch
indicadores_crunch_pot1How many potential indicators needed
strings_de_folha_crunch_lc4Don't crunch words with long lower case strings
crunch_leave_uc_strings4Don't crunch words with long lower case strings
crunch_long_repetitions3Crunch words with long repetitions
crunch_debug0As it says
fixsp_non_noise_limit1How many non-noise blbs either side?
fixsp_modo_concluído1What constitues done for spacing
debug_fix_space_level0Contextual fixspace debug
x_ht_tolerância_de_aceitação8Max allowed deviation of blob top outside of font data
x_ht_min_change8Min change in xht before actually trying it
superscript_debug0Debug level for sub & superscript fixer
qualidade_jpg85Set JPEG quality level
dpi definido pelo usuário0Specify DPI for input image
min_characters_to_try50Specify minimum characters to try during OSD
suspect_level99Suspect marker level
suspect_short_words2Don't suspect dict wds longer than this
tessedit_modo_rejeitar0Rejection algorithm
tessedit_image_border2Rej blbs near image edge limit
min_sane_x_ht_pixels8Reject any x-ht lt or eq than this
tessedit_page_number-1-1 -> All pages, else specific page to process
tessedit_paralelizar1Run in parallel where possible
lstm_modo_de_escolha2Allows to include alternative symbols choices in the hOCR output. Valid input values are 0, 1 and 2. 0 is the default value. With 1 the alternative symbol choices per timestep are included. With 2 alternative symbol choices are extracted from the CTC process instead of the lattice. The choices are mapped per character.
lstm_choice_iterations5Sets the number of cascading iterations for the Beamsearch in lstm_modo_de_escolha. Note that lstm_modo_de_escolha must be set to a value greater than 0 to produce results.
nível_de_depuração_tosp0Debug data
tosp_espaço_suficiente_amostras_para_mediana3or should we use mean
tosp_redo_kern_limit10No.samples reqd to reestimate for row
tosp_poucas_amostras40No.gaps reqd with 1 large gap to treat as a table
linha_curta_tosp20No.gaps reqd with few cert spaces to use certs
método_de_sanidade_tosp1How to avoid being silly
tamanho_máximo_de_ruído_textord7Pixel size of noise
textord_baseline_debug0Baseline debug level
textord_noise_sizefraction10Fraction of size for maxima
limite de transposição de ruído textord16Transitions for normal blob
textord_noise_sncount1super norm blobs to save row
usar ambiguidades para adaptação0Use ambigs for deciding whether to adapt to a character
priorize_division0Prioritize blob division over chopping
classificar_habilitar_aprendizagem1Enable adaptive classifier
tess_cn_matching0Character Normalized Matching
tess_bn_matching0Baseline Normalized Matching
classificar_ativar_correspondência_adaptativa1Enable adaptive classifier
classificar_usar_modelos_pré_adaptados0Use pre-adapted classifier templates
classificar_salvar_modelos_adaptados0Save adapted templates to a file
classificar_ativar_depurador_adaptativo0Enable match debugger
classificar_norma_não_linear0Non-linear stroke-density normalization
disable_character_fragments1Do not include character fragments in the results of the classifier
classificar_fragmentos_de_caracteres_de_depuração0Bring up graphical debugging windows for fragments training
matcher_debug_separate_windows0Use two different windows for debugging the matching: One for the protos and one for the features.
classificar_bln_modo_numérico0Assume the input is numbers [0-9].
carregar_sistema_cão1Load system word dawg.
carregar_freq_dawg1Load frequent word dawg.
carregar_cão_sem_ambiguidade1Load unambiguous word dawg.
carregar_punc_dawg1Load dawg with punctuation patterns.
carregar_número_cão1Load dawg with number patterns.
carregar_bigram_dawg1Load dawg with special word bigrams.
use_only_first_uft8_step0Use only the first UTF8 step of the given string when computing log probabilities.
stopper_sem_escolhas_aceitáveis0Make AcceptableChoice() always return false. Useful when there is a need to explore all segmentations
segmento_não_alfabético_script0Don't use any alphabetic-specific tricks. Set to true in the traineddata config file for scripts that are cursive or inherently fixed-pitch
salvar_palavras_doc0Save Document Words
mesclar_fragmentos_na_matriz1Merge the fragments in the ratings matrix and delete them after merging
wordrec_enable_assoc1Associator Enable
forçar_associação_de_palavras0force associator to run regardless of what enable_assoc is. This is used for CJK where component grouping is necessary.
chop_enable1Chop enable
corte_deslizamento_vertical0Vertical creep
pilha de costura nova1Use new seam_pile
assume_fixed_pitch_char_segment0include fixed-pitch heuristics in char segmentation
wordrec_skip_no_truth_words0Only run OCR for words that had truth recorded in BlamerBundle
wordrec_debug_blamer0Print blamer debug messages
wordrec_run_blamer0Try to set the blame for errors
salvar_opções_alternativas1Save alternative paths found during chopping and segmentation search
language_model_ngram_on0Turn on/off the use of character ngram model
language_model_ngram_use_ only_first_uft8_step0Use only the first UTF8 step of the given string when computing log probabilities.
language_model_ngram_space_delimited_language1Words are delimited by space
language_model_use_sigmoidal_certainty0Use sigmoidal score for certainty
tessedit_resegment_from_boxes0Take segmentation and labeling from box file
tessedit_resegment_from_line_boxes0Conversion of word/line box file to char box file
tessedit_train_from_boxes0Generate training data from boxed chars
tessedit_make_boxes_from_boxes0Generate more boxes from boxed chars
tessedit_train_line_recognizer0Break input into lines and remap boxes if present
tessedit_dump_pageseg_images0Dump intermediate images made during page segmentation
tessedit_do_invert1Try inverting the image in LSTMRecognizeWord
tessedit_ambigs_treinamento0Perform training for ambiguities
tessedit_adaption_debug0Generate and print debug information for adaption
applybox_learn_chars_and_char_frags_mode0Learn both character fragments (as is done in the special low exposure mode) as well as unfragmented characters.
applybox_learn_ngrams_mode0Each bounding box is assumed to contain ngrams. Only learn the ngrams whose outlines overlap horizontally.
tessedit_exibir_palavras_saídas0Draw output words
tessedit_dump_choices0Dump char choices
tessedit_timing_debug0Print timing stats
tessedit_fix_fuzzy_spaces1Try to improve fuzzy spaces
tessedit_unrej_any_wd0Don't bother with word plausibility
tessedit_fix_hyphens1Crunch double hyphens?
tessedit_enable_doc_dict1Add words to the document dictionary
tessedit_debug_fonts0Output font info per char
tessedit_debug_block_rejection0Block and Row stats
tessedit_ativar_correção_de_bigramas1Enable correction based on the word bigram dictionary.
tessedit_enable_dict_correction0Enable single word correction based on the dictionary.
ativar_remoção_de_ruído1Remove and conditionally reassign small outlines when they confuse layout analysis, determining diacritics vs noise
tessedit_minimal_rej_pass10Do minimal rejection on pass 1 output
tessedit_test_adaption0Test adaption criteria
teste_pt0Test for point
parágrafo_texto_baseado1Run paragraph detection on the post-text-recognition (more accurate)
lstm_use_matrix1Use ratings matrix/beam search with lstm
tessedit_boa_qualidade_não_rej1Reduce rejection on good docs
tessedit_use_reject_spaces1Reject spaces?
tessedit_preserve_blk_rej_perfect_wds1Only rej partially rejected words in block rejection
tessedit_preserve_row_rej_perfect_wds1Only rej partially rejected words in row rejection
tessedit_dont_blkrej_good_wds0Use word segmentation quality metric
tessedit_dont_rowrej_good_wds0Use word segmentation quality metric
tessedit_row_rej_good_docs1Apply row rejection to good docs
tessedit_reject_bad_qual_wds1Reject all bad quality wds
tessedit_debug_doc_rejection0Page stats
tessedit_debug_quality_metrics0Output data to debug file
bland_unrej0unrej potential with no checks
unlv_tilde_crunching0Mark v.bad words for tilde crunch
hocr_font_info0Add font info to hocr output
hocr_char_boxes0Add coordinates for each character to hocr output
crunch_early_merge_tess_fails1Before word crunch?
crunch_early_convert_bad_unlv_chs0Take out ~^ early?
crunch_terrible_garbage1As it says
strings_de_saída_ok_crunch1Don't touch sensible strings
crunch_accept_ok1Use acceptability in okstring
crunch_leave_accept_strings0Don't pot crunch sensible strings
crunch_include_numerals0Fiddle alpha figures
tessedit_prefer_joined_punct0Reward punctuation joins
tessedit_write_block_separators0Write block separators in output
tessedit_write_rep_codes0Write repetition char code
tessedit_write_unlv0Write .unlv output file
tessedit_create_txt0Write .txt output file
tessedit_create_hocr0Write .html hOCR output file
tessedit_create_alto0Write .xml ALTO file
tessedit_create_lstmbox0Write .box file for LSTM training
tessedit_create_tsv0Write .tsv output file
tessedit_create_wordstrbox0Write WordStr format .box output file
tessedit_create_pdf0Write .pdf output file
textonly_pdf0Create PDF with only one invisible text layer
suspect_constrain_1Il0UNLV keep 1Il chars rejected
tessedit_minimal_rejection0Only reject tess failures
tessedit_zero_rejection0Don't reject ANYTHING
tessedit_word_for_word0Make output have exactly one word per WERD
tessedit_zero_kelvin_rejection0Don't reject ANYTHING AT ALL
tessedit_rejection_debug0Adaption debug
tessedit_flip_0O1Contextual 0O O0 flips
rej_trust_doc_dawg0Use DOC dawg in 11l conf. detector
rej_1Il_use_dict_word0Use dictword test
rej_1Il_trust_permuter_type1Don't double check
rej_use_tess_accepted1Individual rejection control
rej_use_tess_blanks1Individual rejection control
rej_use_good_perm1Individual rejection control
rej_use_sensible_wd0Extend permuter check
rej_alphas_in_number_perm0Extend permuter check
tessedit_create_boxfile0Output text with boxes
tessedit_write_images0Capture the image from the IPE
modo_de_exibição_interativo0Run interactively?
tessedit_override_permuter1According to dict_word
tessedit_use_primary_params_model0In multilingual mode use params model of the primary language
textord_tabfind_show_vlines0Debug line finding
textord_use_cjk_fp_model0Use CJK fixed pitch model
poly_allow_detailed_fx0Allow feature extractors to see the original outline
tessedit_init_config_only0Only initialize with the config file. Useful if the instance is not going to be used for OCR but say only for layout analysis.
textord_equation_detect0Turn on equation detector
textord_tabfind_vertical_text1Enable vertical detection
textord_tabfind_force_vertical_text0Force using vertical text page mode
preservar_espaços_entre_palavras0Preserve multiple interword spaces
páginaseg_aplicar_máscara_musical1Detect music staff and remove intersecting components
textord_modo_altura_única0Script has no xheight, so use a single mode
tosp_old_to_method0Space stats use prechopping?
tosp_old_to_constrain_sp_kn0Constrain relative values of inter and intra-word gaps for old_to_method.
tosp_somente_use_prop_rows1Block stats to use fixed pitch rows?
tosp_forçar_quebra_de_palavras_no_ponto0Force word breaks on punct to break long lines in non-space delimited langs
tosp_use_pre_chopping0Space stats use prechopping?
tosp_old_to_bug_fix0Fix suspected bug in old code
tosp_block_use_cert_spaces1Only stat OBVIOUS spaces
tosp_row_use_cert_spaces1Only stat OBVIOUS spaces
tosp_blobs_estreitos_não_certificado1Only stat OBVIOUS spaces
tosp_row_use_cert_spaces11Only stat OBVIOUS spaces
tosp_recovery_isolated_row_stats1Use row alone when inadequate cert spaces
tosp_apenas_pequenos_espaços_para_kern0Better guess
tosp_all_flips_fuzzy0Pass ANY flip to context?
tosp_fuzzy_limit_all1Don't restrict kn->sp fuzzy limit to tables
textord_sem_rejeições0Don't remove noise blobs
textord_mostrar_blobs0Display unsorted blobs
textord_mostrar_caixas0Display unsorted blobs
textord_ruído_rejwords1Reject noise-like words
textord_noise_rejrows1Reject noise-like rows
textord_ruído_depuração0Debug row garbage detector
classificar_aprender_depurar_strClass str to debug learning
arquivo_de_palavras_do_usuárioA filename of user-provided words.
sufixo_palavras_do_usuárioA suffix of user-provided words located in tessdata.
arquivo_de_padrões_do_usuárioA filename of user-provided patterns.
sufixo_padrões_de_usuárioA suffix of user-provided patterns located in tessdata.
arquivo de palavras ambíguas de saídaOutput file for ambiguities found in the dictionary
palavra_para_depurarWord for which stopper debug information should be printed to stdout
tessedit_char_blacklistBlacklist of chars not to recognize
tessedit_char_whitelistWhitelist of chars to recognize
tessedit_char_unblacklistList of chars to override tessedit_char_blacklist
tessedit_write_params_to_fileWrite all parameters to the given file.
aplicar_padrão_de_exposição_da_caixa.expExposure value follows this pattern in the image filename. The name of the image files are expected to be in the form [lang].[fontname].exp [num].tif
chs_leading_punct('`"Pontuação inicial
chs_trailing_punct1).,;:?!1st Trailing punctuation
chs_trailing_punct2)'`"2nd Trailing punctuation
contornos_ímpares%|Número não padrão de contornos
outlines_2ij!?%":;Número não padrão de contornos
pontuação_numérica.,Punct. chs expected WITHIN numbers
caractere_não_reconhecido|Output char for unidentified blobs
ok_repeated_ch_non_alphanum_wds-?*=Allow NN to unrej
conflito_conjunto_I_l_1Il1 []Il1 conflict set
tipo_de_arquivo.tifFilename extension
tessedit_load_sublangsList of languages to load with this one
separador_de_páginaPage separator (default is form feed control character)
classificar_char_norm_range0.2Character Normalization Range ...
classificar_taxa_máxima1.5Veto ratio between classifier ratings
classificar_margem_de_certeza_máxima5.5Veto difference between classifier certainties
matcher_good_threshold0.125Good Match (0-1)
resultado_adaptativo_confiável_do_matcher0Great Match (0-1)
limiar_perfeito_do_correspondente0.02Perfect Match (0-1)
matcher_bad_match_pad0.15Bad Match Pad (0-1)
margem_de_classificação_do_comparador0.1New template margin (0-1)
matcher_avg_noise_size12Avg. noise blob length
matcher_clustering_max_angle_delta0.015Maximum angle delta for prototype clustering
penalização_de_lixo_desajustado0Penalty to apply when a non-alnum is vertically out of its expected textline position
escala_de_avaliação1.5Rating scaling factor
escala_de_certeza20Certainty scaling factor
tessedit_class_miss_scale0.00390625Scale factor for features not used
fator_de_poda_adaptado_classificar2.5Prune poor adapted results this much worse than best result
limiar de poda adaptado de classificação-1Threshold at which fator_de_poda_adaptado_classificar starts
classificar_fragmentos_de_caracteres_lixo_limiar_de_certeza-3Exclude fragments that do not look like whole characters from training and adaption
tamanho_máximo_grande_do_speckle0.3Max large speckle size
penalidade_de_classificação_speckle10Penalty to add to worst rating for noise
xheight_penalty_subscripts0.125Score penalty (0.1 = 10%) added if there are subscripts or superscripts in a word, but it is otherwise OK.
penalidade_altura_x_inconsistente0.25Score penalty (0.1 = 10%) added if an xheight is inconsistent.
segment_penalty_dict_frequent_word1Score multiplier for word matches which have good case and are frequent in the given language (lower is better).
segment_penalty_dict_case_ok1.1Score multiplier for word matches that have good case (lower is better).
segment_penalty_dict_case_bad1.3125Default score multiplier for word matches, which may have case issues (lower is better).
segment_penalidade_dict_nonword1.25Score multiplier for glyph fragment segmentations which do not match a dictionary word (lower is better).
escala_de_certeza20Certainty scaling factor
stopper_nondict_certainty_base-2.5Certainty threshold for non-dict words
stopper_phase2_certainty_rejection_offset1Reject certainty offset
stopper_certainty_per_char-0.5Certainty to add for each dict char above small word size.
stopper_allowable_character_badness3Max certaintly variation allowed in a word (in sigma)
doc_dict_pending_threshold0Worst certainty for using pending dictionary
doc_dict_certainty_threshold-2.25Worst certainty for words that can be inserted into the document dictionary
tessedit_certainty_threshold-2.25Good blob limit
chop_split_dist_knob0.5Split length adjustment
chop_overlap_knob0.9Split overlap adjustment
chop_center_knob0.15Split center adjustment
chop_sharpness_knob0.06Split sharpness adjustment
chop_width_change_knob5Width change adjustment
chop_ok_split100OK split limit
chop_good_split50Good split limit
segsearch_max_char_wh_ratio2Proporção máxima entre largura e altura dos caracteres

Para obter melhores resultados, recomenda-se usar os filtros de pré-processamento de imagem do IronOCR antes de aplicar o OCR. Esses filtros podem melhorar drasticamente a precisão, especialmente ao trabalhar com digitalizações de baixa qualidade ou documentos complexos, como tabelas .

Perguntas frequentes

Como configuro o IronTesseract para OCR em C#?

Para configurar o IronTesseract, crie uma instância do IronTesseract e defina propriedades como Idioma e Configuração. Você pode especificar o idioma do OCR (dentre 125 idiomas suportados), habilitar a leitura de código de barras, configurar a saída em PDF pesquisável e definir a lista de caracteres permitidos. Por exemplo: var tesseract = new IronOcr.IronTesseract { Language = IronOcr.OcrLanguage.English, Configuration = new IronOcr.TesseractConfiguration { ReadBarCodes = false, RenderSearchablePdf = true } };

Quais formatos de entrada o IronTesseract suporta?

O IronTesseract aceita diversos formatos de entrada através da classe OcrInput. Você pode processar imagens (PNG, JPG, etc.), arquivos PDF e documentos digitalizados. A classe OcrInput oferece métodos flexíveis para carregar esses diferentes formatos, facilitando a execução de OCR em praticamente qualquer documento que contenha texto.

Posso ler códigos de barras juntamente com texto usando o IronTesseract?

Sim, o IronTesseract inclui recursos avançados de leitura de código de barras. Você pode habilitar a detecção de código de barras definindo `ReadBarCodes = true` na configuração do Tesseract. Isso permite extrair dados de texto e código de barras do mesmo documento em uma única operação de OCR.

Como faço para criar PDFs pesquisáveis a partir de documentos digitalizados?

O IronTesseract pode converter documentos e imagens digitalizados em PDFs pesquisáveis definindo `RenderSearchablePdf = true` na configuração do Tesseract. Isso cria arquivos PDF onde o texto é selecionável e pesquisável, mantendo a aparência original do documento.

Quais idiomas o IronTesseract suporta para OCR?

O IronTesseract suporta 125 idiomas internacionais para reconhecimento de texto. Você pode especificar o idioma definindo a propriedade `Language` na sua instância do IronTesseract, como `IronOcr.OcrLanguage.English`, `Spanish`, `Chinese`, `Arabic` e muitos outros.

Posso restringir quais caracteres são reconhecidos durante o OCR?

Sim, o IronTesseract permite a criação de listas de permissão e bloqueio de caracteres através da propriedade WhiteListCharacters em TesseractConfiguration. Esse recurso ajuda a melhorar a precisão quando você conhece o conjunto de caracteres esperado, como, por exemplo, limitar o reconhecimento apenas a caracteres alfanuméricos.

Como faço para realizar OCR em vários documentos simultaneamente?

O IronTesseract oferece suporte a recursos multithread para processamento em lote. Você pode aproveitar o processamento paralelo para realizar OCR em vários documentos simultaneamente, melhorando significativamente o desempenho ao lidar com grandes volumes de imagens ou PDFs.

Qual versão do Tesseract o IronOCR utiliza?

O IronOCR utiliza uma versão personalizada e otimizada do Tesseract 5, conhecida como Iron Tesseract. Este mecanismo aprimorado oferece maior precisão e desempenho em comparação com as implementações padrão do Tesseract, mantendo a compatibilidade com aplicativos .NET.

Como o IronOCR pode melhorar a precisão dos dados?

O IronOCR melhora a precisão dos dados através de seus algoritmos avançados de reconhecimento e recursos de correção de imagem, assegurando que o processo de extração de texto seja tanto confiável quanto preciso.

Há uma avaliação gratuita disponível para o IronOCR?

Sim, o Iron Software oferece uma avaliação gratuita do IronOCR, permitindo que os usuários testem seus recursos e capacidades antes de tomar uma decisão de compra.

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais
Analisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente de Programa Principal - Equipe da Comunidade .NET
Jeff também é Gerente de Programa Principal das equipes do .NET e do Visual Studio. Ele é o produtor executivo da série de conferências virtuais .NET Conf e apresenta o "Fritz and Friends", uma transmissão ao vivo para desenvolvedores que vai ao ar duas vezes por semana, onde ele conversa sobre tecnologia e escreve código junto com os espectadores. Jeff cria workshops, apresentações e planeja conteúdo para os maiores eventos de desenvolvedores da Microsoft, incluindo o Microsoft Build, o Microsoft Ignite, a .NET Conf e o Microsoft MVP Summit.
Pronto para começar?
Nuget Baixar 6,175,195 | Versão: 2026.7 recém-lançado
Still Scrolling Icon

Ainda está rolando a tela?

Quer provas rápidas? PM > Install-Package IronOcr
executar um exemplo Veja sua imagem se transformar em texto pesquisável.