Background.

AOI software needs to use the OCR feature to recognize the texts on the chips. Because our vision software is based on OpenCV, so the first choice is text module in opencv_contrib. 

Prerequisites.

1. CMake version installed with version >= 3.15.

2. Visual Studio 2019

Procedures.

1. OCR module is not in standard OpenCV package. It is in text module of OpenCV_Contrib. It can be downloaded from opencv_contrib.

2. The core of OCR is using Tesseract, and Tesseract depends on Leptonica, so need to build both Leptonica and Tesseract first.

3. Get the Leptonica from https://github.com/DanBloomberg/leptonica. Use CMake to configure the project, disable the option SW_BUILD. After generate project, start Vistual Studio 2019 as administrator, open the solution, and build the solution. Then then build the Install project, the Leptonica should be installed in "C:\Program Files (x86)\leptonica".

4. Get the Tesseract from https://github.com/tesseract-ocr/tesseract. Use CMake to configure the project and set Leptonica_DIR to the last steps install path "C:\Program Files (x86)\leptonica". Open the solution with administrator, build the solution, and build the install project. Copy down the install path.

5. Use CMake to config the OpenCV solution. Copy the text module from opencv_contrib to .\OpenCV\sources\modules. Run CMake_Gui, there are 3 options need to set. Tesseract_DIR, Tesseract_Include_Dir, Tesseract_Library. Tesseract_DIR set to last step path. After set, can run CMake to config and generate the solution.

6. Open the OpenCV solution. Open the .\modules\text\src\precomp.hpp file, change the include path to as below.

#define HAVE_TESSERACT // Add this line

#ifdef HAVE_TESSERACT
#include <tesseract/baseapi.h>
#include <tesseract/resultiterator.h>
#endif

7. Download the language test data from https://github.com/tesseract-ocr/tessdata. What i use is the eng.traineddata. Put it to .\tesseract\tessdata.

8. After build OpenCV successfully, then you can create the TestOpenCV project with the below function, before running it, need to copy the tesseract41.dll to the output folder(where the exe file is put).

using OCRTesseract =  cv::text::OCRTesseract;
void TestOCR()
{    
    cv::Mat mat = cv::imread(".\\data\\OCRTest.png");
    if ( mat.empty() )
        return;

    std::string output_text;
    char *dataPath = "C:/tesseract-build/tesseract/tessdata";
    cv::Ptr<OCRTesseract> ptrOcr = OCRTesseract::create(dataPath);
    ptrOcr->run(mat, output_text );
    cout << output_text << endl;
}

 9. The Tesseract is sensitive to the text orientation. So need to make the text face up to be better recognized.

posted on 2020-01-02 15:42  xsgluozi  阅读(676)  评论(0编辑  收藏  举报