OCR C++ Tesseract按行识别字符

这个程序演示Tesseract OCR按行识别字符。

不仅显示识别结果,还找出每行文本的bounding box(边界框/包围盒)。

输入图片:

程序运行后会在CMD里打印识别结果:

解释一下:在图片里找到了8行文本。

矩形边界框0的左上角坐标是(31,87),宽度是554,高度是40,置信度是94.

把矩形框绘制到输入图片里,大概就是这样:

代码:

cpp 复制代码
#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 path
  if (api->Init(NULL, "eng")) {
      fprintf(stderr, "Could not initialize tesseract.\n");
      exit(1);
  }
  Pix *image = pixRead("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 memory
  api->End();
  delete api;
  delete [] outText;
  pixDestroy(&image);

  return 0;
}
相关推荐
小弥儿15 小时前
GitHub今日热榜 | 2026-07-19
人工智能·学习·github·知识图谱
犀利豆15 小时前
写 Mermaid 总在查语法?我做了个用一句话生成图的小工具 - text2mermaid
人工智能
墨舟的AI笔记15 小时前
端侧推理后端:ONNX Runtime 与跨平台执行提供方
人工智能
阿米亚波15 小时前
【C++】流式数据输入处理(不完全整理)
开发语言·c++·笔记
大模型码小白16 小时前
JAVA 集合框架进阶:List 与 Set 的深度解析与实战
java·开发语言·人工智能·windows·语言模型·list·ai编程
IT_陈寒16 小时前
为什么我的JavaScript异步代码总是不按顺序执行?
前端·人工智能·后端
石头dhf17 小时前
Claude code执行过程
人工智能
小码哥哥17 小时前
云原生时代的企业AI知识库:从云生态融合到多云知识治理
人工智能·云原生
皓月斯语17 小时前
【C++基础】三目运算符
开发语言·数据结构·c++