ocr_tesseract.cpp 9.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/ml.hpp"

#include <iostream>
#include <fstream>
#include <queue>

namespace cv
{
namespace text
{

56 57 58 59 60 61
using namespace std;

void OCRTesseract::run(Mat& image, string& output_text, vector<Rect>* component_rects,
                       vector<string>* component_texts, vector<float>* component_confidences,
                       int component_level)
{
62
    CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
63 64 65 66 67 68 69 70 71
    CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
    output_text.clear();
    if (component_rects != NULL)
        component_rects->clear();
    if (component_texts != NULL)
        component_texts->clear();
    if (component_confidences != NULL)
        component_confidences->clear();
}
72

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
void OCRTesseract::run(Mat& image, Mat& mask, string& output_text, vector<Rect>* component_rects,
                       vector<string>* component_texts, vector<float>* component_confidences,
                       int component_level)
{
    CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
    CV_Assert( mask.type() == CV_8UC1 );
    CV_Assert( (component_level == OCR_LEVEL_TEXTLINE) || (component_level == OCR_LEVEL_WORD) );
    output_text.clear();
    if (component_rects != NULL)
        component_rects->clear();
    if (component_texts != NULL)
        component_texts->clear();
    if (component_confidences != NULL)
        component_confidences->clear();
}

previ's avatar
previ committed
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
CV_WRAP String OCRTesseract::run(InputArray image, int min_confidence, int component_level)
{
    std::string output1;
    std::string output2;
    vector<string> component_texts;
    vector<float> component_confidences;
    Mat image_m = image.getMat();
    run(image_m, output1, NULL, &component_texts, &component_confidences, component_level);
    for(unsigned int i = 0; i < component_texts.size(); i++)
    {
        // cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;
        if(component_confidences[i] > min_confidence)
        {
            output2 += component_texts[i];
        }
    }
    return String(output2);
}

CV_WRAP String OCRTesseract::run(InputArray image, InputArray mask, int min_confidence, int component_level)
{
    std::string output1;
    std::string output2;
    vector<string> component_texts;
    vector<float> component_confidences;
    Mat image_m = image.getMat();
    Mat mask_m = mask.getMat();
    run(image_m, mask_m, output1, NULL, &component_texts, &component_confidences, component_level);
    for(unsigned int i = 0; i < component_texts.size(); i++)
    {
        cout << "confidence: " << component_confidences[i] << " text:" << component_texts[i] << endl;

        if(component_confidences[i] > min_confidence)
        {
            output2 += component_texts[i];
        }
    }
    return String(output2);
}


lluis's avatar
lluis committed
130
class OCRTesseractImpl : public OCRTesseract
131
{
lluis's avatar
lluis committed
132 133 134 135
private:
#ifdef HAVE_TESSERACT
    tesseract::TessBaseAPI tess;
#endif
136

lluis's avatar
lluis committed
137 138 139 140 141 142
public:
    //Default constructor
    OCRTesseractImpl(const char* datapath, const char* language, const char* char_whitelist, int oemode, int psmode)
    {

#ifdef HAVE_TESSERACT
143 144 145 146 147 148 149 150 151
        const char *lang = "eng";
        if (language != NULL)
            lang = language;

        if (tess.Init(datapath, lang, (tesseract::OcrEngineMode)oemode))
        {
            cout << "OCRTesseract: Could not initialize tesseract." << endl;
            throw 1;
        }
152

153
        //cout << "OCRTesseract: tesseract version " << tess.Version() << endl;
154

155 156
        tesseract::PageSegMode pagesegmode = (tesseract::PageSegMode)psmode;
        tess.SetPageSegMode(pagesegmode);
157

158 159 160 161
        if(char_whitelist != NULL)
            tess.SetVariable("tessedit_char_whitelist", char_whitelist);
        else
            tess.SetVariable("tessedit_char_whitelist", "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
162

163
        tess.SetVariable("save_best_choices", "T");
lluis's avatar
lluis committed
164
#else
165 166 167 168 169 170 171
        cout << "OCRTesseract("<<oemode<<psmode<<"): Tesseract not found." << endl;
        if (datapath != NULL)
            cout << "            " << datapath << endl;
        if (language != NULL)
            cout << "            " << language << endl;
        if (char_whitelist != NULL)
            cout << "            " << char_whitelist << endl;
lluis's avatar
lluis committed
172 173
#endif
    }
174

lluis's avatar
lluis committed
175 176 177
    ~OCRTesseractImpl()
    {
#ifdef HAVE_TESSERACT
178
        tess.End();
lluis's avatar
lluis committed
179 180
#endif
    }
181

lluis's avatar
lluis committed
182 183 184 185 186
    void run(Mat& image, string& output, vector<Rect>* component_rects=NULL,
             vector<string>* component_texts=NULL, vector<float>* component_confidences=NULL,
             int component_level=0)
    {

187
        CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );
188

189
#ifdef HAVE_TESSERACT
190

191 192 193 194 195 196 197 198 199
        if (component_texts != 0)
            component_texts->clear();
        if (component_rects != 0)
            component_rects->clear();
        if (component_confidences != 0)
            component_confidences->clear();

        tess.SetImage((uchar*)image.data, image.size().width, image.size().height, image.channels(), image.step1());
        tess.Recognize(0);
lluis's avatar
lluis committed
200 201 202 203
        char *outText;
        outText = tess.GetUTF8Text();
        output = string(outText);
        delete [] outText;
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

        if ( (component_rects != NULL) || (component_texts != NULL) || (component_confidences != NULL) )
        {
            tesseract::ResultIterator* ri = tess.GetIterator();
            tesseract::PageIteratorLevel level = tesseract::RIL_WORD;
            if (component_level == OCR_LEVEL_TEXTLINE)
                level = tesseract::RIL_TEXTLINE;

            if (ri != 0) {
                do {
                    const char* word = ri->GetUTF8Text(level);
                    if (word == NULL)
                        continue;
                    float conf = ri->Confidence(level);
                    int x1, y1, x2, y2;
                    ri->BoundingBox(level, &x1, &y1, &x2, &y2);

                    if (component_texts != 0)
                        component_texts->push_back(string(word));
                    if (component_rects != 0)
                        component_rects->push_back(Rect(x1,y1,x2-x1,y2-y1));
                    if (component_confidences != 0)
                        component_confidences->push_back(conf);

                    delete[] word;
                } while (ri->Next(level));
            }
            delete ri;
232 233
        }

234
        tess.Clear();
235

lluis's avatar
lluis committed
236
#else
237

238 239 240 241 242 243 244 245
        cout << "OCRTesseract(" << component_level << image.type() <<"): Tesseract not found." << endl;
        output.clear();
        if(component_rects)
            component_rects->clear();
        if(component_texts)
            component_texts->clear();
        if(component_confidences)
            component_confidences->clear();
246
#endif
lluis's avatar
lluis committed
247 248
    }

249 250 251 252 253 254 255 256 257 258
    void run(Mat& image, Mat& mask, string& output, vector<Rect>* component_rects=NULL,
             vector<string>* component_texts=NULL, vector<float>* component_confidences=NULL,
             int component_level=0)
    {
        CV_Assert( mask.type() == CV_8UC1 );
        CV_Assert( (image.type() == CV_8UC1) || (image.type() == CV_8UC3) );

        run( mask, output, component_rects, component_texts, component_confidences, component_level);
    }

previ's avatar
previ committed
259 260 261 262 263 264 265 266
    void setWhiteList(const String& char_whitelist)
    {
  #ifdef HAVE_TESSERACT
        tess.SetVariable("tessedit_char_whitelist", char_whitelist.c_str());
  #else
        (void)char_whitelist;
  #endif
    }
lluis's avatar
lluis committed
267 268
};

269 270
Ptr<OCRTesseract> OCRTesseract::create(const char* datapath, const char* language,
                                       const char* char_whitelist, int oem, int psmode)
lluis's avatar
lluis committed
271
{
previ's avatar
previ committed
272
    return makePtr<OCRTesseractImpl>(datapath, language, char_whitelist, oem, psmode);
lluis's avatar
lluis committed
273
}
274 275 276 277


}
}