C++实例 调用Tesseract OCR的API

C++实例 调用Tesseract OCR的API

    • 1. 前言
    • 2. 模式
    • 3. 调用方式C++ Examples**【转自官网】
      • `3.1 Basic_example`
      • `3.2 SetRectangle_example`
      • `3.3 GetComponentImages_example`
      • `3.4 ResultIterator_example`
      • `3.5 OSD_example`
      • `3.6 LSTM_Choices_example`
      • `3.7 OpenCV_example`
      • `3.8 UserPatterns_example`

1. 前言

Tesseract OCR支持不同调用方式(详情请看具体实例),同一种调用方式也可以设置不同模式。
调用方法或模式不同,对OCR识别结果的精度有一定影响。模式设置不同,输出的结果格式也不一致。
实际项目中,需要根据需求比较各方法的优劣从而选择最合适的。

2. 模式

构造体定义
enum PageIteratorLevel {RIL_BLOCK,    // Block of text/image/separator line.RIL_PARA,     // Paragraph within a block.RIL_TEXTLINE, // Line within a paragraph.RIL_WORD,     // Word within a textline.RIL_SYMBOL    // Symbol/character within a word.
};

RIL_BLOCK:把原稿分割成不同区域,按区域识别文字,OCR结果是每个区域的字符串
RIL_TEXTLINE:按行识别文字,OCR结果是一行一行的字符串
RIL_WORD: 按单词识别文字,OCR结果是一个一个的单词
RIL_SYMBOL:按字符识别文字,OCR结果是一个一个的字符

3. 调用方式C++ Examples**【转自官网】

C++API实例:https://tesseract-ocr.github.io/tessdoc/Examples_C++.html
API实例:https://tesseract-ocr.github.io/tessdoc/#api-examples

注意
如果C++的实例代码编译不通过,可能是需要添加以下头文件

#include <leptonica/pix_internal.h>

3.1 Basic_example

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>int main()
{char *outText;tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();// Initialize tesseract-ocr with English, without specifying tessdata pathif (api->Init(NULL, "eng")) {fprintf(stderr, "Could not initialize tesseract.\n");exit(1);}// Open input image with leptonica libraryPix *image = pixRead("/usr/src/tesseract/testing/phototest.tif");api->SetImage(image);// Get OCR resultoutText = api->GetUTF8Text();printf("OCR output:\n%s", outText);// Destroy used object and release memoryapi->End();delete api;delete [] outText;pixDestroy(&image);return 0;
}

3.2 SetRectangle_example

如果只想识别特定区域的文字,可以用这个方法。需提前设定指定区域的坐标。

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>int main()
{char *outText;tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();// Initialize tesseract-ocr with English, without specifying tessdata pathif (api->Init(NULL, "eng")) {fprintf(stderr, "Could not initialize tesseract.\n");exit(1);}// Open input image with leptonica libraryPix *image = pixRead("/usr/src/tesseract/testing/phototest.tif");api->SetImage(image);// Restrict recognition to a sub-rectangle of the image// SetRectangle(left, top, width, height)api->SetRectangle(30, 86, 590, 100);// Get OCR resultoutText = api->GetUTF8Text();printf("OCR output:\n%s", outText);// Destroy used object and release memoryapi->End();delete api;delete [] outText;pixDestroy(&image);return 0;
}

3.3 GetComponentImages_example

以Box的形式返回OCR结果

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>int main()
{char *outText;tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();// Initialize tesseract-ocr with English, without specifying tessdata pathif (api->Init(NULL, "eng")) {fprintf(stderr, "Could not initialize tesseract.\n");exit(1);}Pix *image = pixRead("/usr/src/tesseract/testing/phototest.tif");api->SetImage(image);Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, NULL, NULL);printf("Found %d textline image components.\n", boxes->n);for (int i = 0; i < boxes->n; i++) {BOX* box = boxaGetBox(boxes, i, L_CLONE);api->SetRectangle(box->x, box->y, box->w, box->h);char* ocrResult = api->GetUTF8Text();int conf = api->MeanTextConf();fprintf(stdout, "Box[%d]: x=%d, y=%d, w=%d, h=%d, confidence: %d, text: %s",i, box->x, box->y, box->w, box->h, conf, ocrResult);boxDestroy(&box);}// Destroy used object and release memoryapi->End();delete api;delete [] outText;pixDestroy(&image);return 0;
}

3.4 ResultIterator_example

以迭代器的形式返回OCR结果

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>int main()
{char *outText;tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();// Initialize tesseract-ocr with English, without specifying tessdata pathif (api->Init(NULL, "eng")) {fprintf(stderr, "Could not initialize tesseract.\n");exit(1);}Pix *image = pixRead("/usr/src/tesseract/testing/phototest.tif");api->SetImage(image);api->Recognize(0);tesseract::ResultIterator* ri = api->GetIterator();tesseract::PageIteratorLevel level = tesseract::RIL_WORD;if (ri != 0) {do {const char* word = ri->GetUTF8Text(level);float conf = ri->Confidence(level);int x1, y1, x2, y2;ri->BoundingBox(level, &x1, &y1, &x2, &y2);printf("word: '%s';  \tconf: %.2f; BoundingBox: %d,%d,%d,%d;\n",word, conf, x1, y1, x2, y2);delete[] word;} while (ri->Next(level));}// Destroy used object and release memoryapi->End();delete api;delete [] outText;pixDestroy(&image);return 0;
}

3.5 OSD_example

如果需要判断文字的方向,可以参考这各个方法

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>int main()
{const char* inputfile = "/tesseract/testing/devatest-rotated-270.png";PIX *image = pixRead(inputfile);tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();api->Init(NULL, "osd");api->SetPageSegMode(tesseract::PSM_OSD_ONLY);api->SetImage(image);int orient_deg;float orient_conf;const char* script_name;float script_conf;api->DetectOrientationScript(&orient_deg, &orient_conf, &script_name, &script_conf);printf("************\n Orientation in degrees: %d\n Orientation confidence: %.2f\n"" Script: %s\n Script confidence: %.2f\n",orient_deg, orient_conf,script_name, script_conf);// Destroy used object and release memoryapi->End();delete api;pixDestroy(&image);return 0;
}

3.6 LSTM_Choices_example

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
int main()
{tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();
// Initialize tesseract-ocr with English, without specifying tessdata pathif (api->Init(NULL, "eng")) {fprintf(stderr, "Could not initialize tesseract.\n");exit(1);}
// Open input image with leptonica libraryPix *image = pixRead("choices.png");api->SetImage(image);
// Set lstm_choice_mode to alternative symbol choices per character, bbox is at word level.api->SetVariable("lstm_choice_mode", "2");api->Recognize(0);tesseract::PageIteratorLevel level = tesseract::RIL_WORD;tesseract::ResultIterator* res_it = api->GetIterator();
// Get confidence level for alternative symbol choices. Code is based on 
// https://github.com/tesseract-ocr/tesseract/blob/main/src/api/hocrrenderer.cpp#L325-L344std::vector<std::vector<std::pair<const char*, float>>>* choiceMap = nullptr;if (res_it != 0) {do {const char* word;float conf;int x1, y1, x2, y2, tcnt = 1, gcnt = 1, wcnt = 0;res_it->BoundingBox(level, &x1, &y1, &x2, &y2);choiceMap = res_it->GetBestLSTMSymbolChoices();for (auto timestep : *choiceMap) {if (timestep.size() > 0) {for (auto & j : timestep) {conf = int(j.second * 100);word =  j.first;printf("%d  symbol: '%s';  \tconf: %.2f; BoundingBox: %d,%d,%d,%d;\n",wcnt, word, conf, x1, y1, x2, y2);gcnt++;}tcnt++;}wcnt++;printf("\n");}} while (res_it->Next(level));}
// Destroy used object and release memoryapi->End();delete api;pixDestroy(&image);return 0;
}

3.7 OpenCV_example

/*
Windows compile example:

SET TESS_INSTALATION=C:/win64
SET OPENCV_INSTALATION=C:/opencv/build
cl OpenCV_example.cc -I %TESS_INSTALATION%/include -I %OPENCV_INSTALATION%/include /link /LIBPATH:%TESS_INSTALATION%/lib /LIBPATH:%OPENCV_INSTALATION%/x64/vc14/lib tesseract51.lib leptonica-1.83.0.lib opencv_world460.lib /machine:x64

*/

#include <leptonica/allheaders.h>
#include <opencv2/opencv.hpp>
#include
#include <tesseract/baseapi.h>

int main(int argc, char *argv[]) {

std::string outText, imPath = argv[1];
cv::Mat im = cv::imread(imPath, cv::IMREAD_COLOR);
tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();

api->Init(NULL, “eng”, tesseract::OEM_LSTM_ONLY);
api->SetPageSegMode(tesseract::PSM_AUTO);
api->SetImage(im.data, im.cols, im.rows, 3, im.step);
outText = std::string(api->GetUTF8Text());
std::cout << outText;
api->End();
delete api;
return 0;
}

3.8 UserPatterns_example

#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>int main()
{Pix *image;char *outText;char *configs[]={"path/to/my.patterns.config"};int configs_size = 1;tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI();if (api->Init(NULL, "eng", tesseract::OEM_LSTM_ONLY, configs, configs_size, NULL, NULL, false)) {fprintf(stderr, "Could not initialize tesseract.\n");exit(1);}image = pixRead("Arial.png");api->SetImage(image);outText = api->GetUTF8Text();printf(outText);api->End();delete api;delete [] outText;pixDestroy(&image);return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/140560.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vue做的一个一点就转的转盘(音乐磁盘),点击停止时会在几秒内缓慢停止,再次点击按钮可以再次旋转,

先看效果&#xff1a; 代码&#xff1a;主要部分我会红线画出来 css:部分&#xff1a; 源码&#xff1a; vue部分&#xff1a; <template><div class"song-lyric"><div><div class"type"><div class"right">&l…

如何用自然语言 5 分钟构建个人知识库应用?我的 GPTs builder 尝试

开发者的想象力闸门一旦打开&#xff0c;迎接我们的必然是目不暇接的 AI 应用浪潮冲击。 兴奋 早晨&#xff0c;我突然发现 ChatGPT 最新的 Create GPTs 功能可以用了。 这太让我意外了&#xff0c;没想到这么快。根据页面上的提示&#xff0c;我一直以为还得等上一周左右。于是…

3C制造RFID产线智能化升级改造设计方案

3C行业需求 近年来&#xff0c;随着政策的支持、相关技术的进步以及市场需求的推动&#xff0c;3C行业迅速发展&#xff0c;我国的3C市场已经进入了稳定发展阶段&#xff0c;作为仅次于汽车产业的大市场&#xff0c;3C产业在智能制造的推动下&#xff0c;越来越多的物联网技术…

软考网络工程师知识点总结(四)

目录 61、FTP文件传输服务 62、DHCP动态主机配置协议 63、电子邮件服务 64、各种新技术相关概念及功能的考查 65、Windows的ipconfig命令 66、Windows的其它命令及说明 67、Linux系统关机和重启命令 68、Linux系统文件属性命令 69、SNMP协议版本 70、SNMP协议的报文类…

【OpenCV(3)】linux arm aarch 是 opencv 交叉编译与使用

文章目录 1、直接找github 别人编译好的2、自主编译参考 3使用CMake检查 参考 1、直接找github 别人编译好的 测试很多&#xff0c;找到一个可用的。 https://github.com/dog-qiuqiu/libopencv 它用了超级模块&#xff01; OpenCV的world模块也称为超级模块&#xff08;supe…

Zeitgeist ZTG Token以及其预测市场加入Moonbeam生态

波卡上的首选多链开发平台Moonbeam宣布与Zeitgeist达成XCM集成&#xff0c;将ZTG Token引入Moonbeam。此集成将使波卡内的Moonbeam和Zeitgeist网络之间的流动性得以流动&#xff0c;并通过Moonbeam的互连合约实现远程链集成。 Zeitgeist是一个基于波卡的Substrate区块链框架构…

5个最佳开源RPA框架

在最近两年中&#xff0c;RPA加上AI&#xff0c;即智能自动化流程&#xff0c;已经成为频繁讨论的话题&#xff0c;特别是在企业和机构的数字化转型过程中。自动化与智能化成为了提高效率的关键手段&#xff0c;而RPA便是迈向这一未来的起始步骤。 可以将RPA视为人体的躯干神经…

[MySQL] MySQL库的基础操作

文章目录 一、数据库的创建 1、1 库的创建 1、2 字符集与校验规则 1、2、1 查看字符集与校验规则 1、2、2 字符集与校验规则的设置 1、2、3 校验规则对数据库的影响 二、数据库的操作 2、1 查看数据库 2、2 删除数据库 2、3 修该数据库 2、4 数据库删除和备份 2、5 显示创建语…

C#医学检验室(LIS)信息管理系统源码

LIS:实验室信息管理系统 (Laboratory Information Management System简称:LIS)。 LIS 是面向医院检验科、检验中心、动物实验所、生物医疗研究所等科研单位研发的集数据采集、传输、存储、分析、处理、发布等功能于一体的信息管理系统。 一、完善的质控&#xff1a; 从样本管理…

芯片设计工程师必备基本功——《设计与验证:Verilog HDL》

Verilog HDL 作为两大硬件描述语言之一&#xff0c;拥有很大的用户群。据调查&#xff0c;目前美国有 90%左右的 IC 设计人员使用 Verilog. 在中国&#xff0c;大概再 50% 左右的人在使用 Verilog 。 大量高校毕业生和部分软件设计人员正在不断涌入这个领域。要想尽快在 IC设计…

mysql 的存储过程

一组为了完成特定功能的sql 语句的集合&#xff0c;写好了存储过程之后&#xff0c;我们可以向函数一样随时调用sql 的集合 CREATE TABLE info ( id int(3) PRIMARY KEY, name VARCHAR(15), score DECIMAL(5,2), pass varchar(12) ); 创建存储过程 创建过程 delimiter $$ #将语…

Python开源项目CodeFormer——人脸重建(Face Restoration),模糊清晰、划痕修复及黑白上色的实践

无论是自己、家人或是朋友、客户的照片&#xff0c;免不了有些是黑白的、被污损的、模糊的&#xff0c;总想着修复一下。作为一个程序员 或者 程序员的家属&#xff0c;当然都有责任满足他们的需求、实现他们的想法。除了这个&#xff0c;学习了本文的成果&#xff0c;或许你还…

git02->gui图形化界面使用,ssh协议,idea集成GIT

gui图形化界面使用ssh协议idea集成GIT 1.gui图形化界面使用 2.ssh协议 git/github生成密钥并通过 操作分为本地电脑配置和github网站配置 第一步&#xff1a;本地电脑配置 右键空白处&#xff0c;选择Git Bash Here打开相关命令窗口 1.配置用户名和邮箱&#xff08;如果已经配…

node插件MongoDB(三)—— 库mongoose 的使用和数据类型(一)

前言 提示&#xff1a;使用mongoose 的前提是你安装了node和 MongoDB。 mongoose 官网文档&#xff1a;http://mongoosejs.net/docs/index.html 文章目录 前言一、安装二、基本使用1. 打开bin目录的mongod.exe文件2. 基本使用的代码&#xff08;连接mongodb 服务&#xff09;3.…

基于《环境影响评价技术导则大气环境(HJ 2.2-2018)》的AERMOD模型配置方法

数值模式模拟是分析大气污染物时空分布和成分贡献的重要工具&#xff0c;利用模拟结果可以分析大气污染的来源、成因、污染程度、持续时间、主要成分、相对贡献等问题&#xff0c;有助于分析并合理控制污染源排放&#xff0c;为产业调整提供参考。当前&#xff0c;针对不同理论…

海思平台awb标定

文章目录 1、raw图采集2、awb标定3、标定效果优化1、raw图采集 raw图采集标准: 如果raw是12bit,即raw12,那么Block9 块的亮度就是40960.8 = 3276.8左右。 勾上Dump Raw,我这里raw10,即Depth为10bit,那么Block19的亮度应该为10240.8 = 819.2左右,调整曝光Exposure Attr…

LED显示屏老化知识

LED显示屏老化是指长时间使用后&#xff0c;LED显示屏性能逐渐下降和衰减的过程。虽然LED显示屏具有较长的寿命和良好的稳定性&#xff0c;但长期使用和环境因素会导致一定程度的老化现象。 LED显示屏为什么会老化 1. 亮度衰减&#xff1a;LED显示屏使用时间越长&#xff0c;LE…

蓝桥杯 选择排序

选择排序的思想 选择排序的思想和冒泡排序类似&#xff0c;是每次找出最大的然后直接放到右边对应位置&#xff0c;然后将最 右边这个确定下来&#xff08;而不是一个一个地交换过去&#xff09;。 再来确定第二大的&#xff0c;再确定第三大的… 对于数组a[]&#xff0c;具体…

keras转onnx,TensorFlow转tf.keras.models.load_model,onnx精度转换

参考&#xff1a; https://blog.csdn.net/Deaohst/article/details/126864267 转onnx 别直接转onnx。 先转PB&#xff1a; import tensorflow as tfmodel_path ./models/model.h5 # 模型文件 model tf.keras.models.load_model(model_path) model.sa…

深入了解springmvc响应数据

目录 一、前后端分离开发与混合开发 1.1 混合开发模式 1.2 前后端分离模式【重点】 二、页面跳转控制 2.1 通过JSP实现页面跳转 2.2 转发与重定向 三、返回JSON数据 3.1 导包与配置 3.2 使用ResponseBody 四、返回静态资源 4.1 为什么无法直接查询静态资源 4.2 配置…