Using tesseract to identify graphic verification code

  tesseract

maven

        <dependency>
            <groupId>org.bytedeco.javacpp-presets</groupId>
            <artifactId>tesseract-platform</artifactId>
            <version>3.04.01-1.3</version>
        </dependency>

Configuration

Create a new testsdata directory under resources directory, and then create a new testsdata directory fromtessdataGet an ENG.traineddata, then create a new configs directory under tessdata directory and set up several configuration files.

  • api_config

tessedit_zero_rejection T

Indicates tessedit_zero_rejection is turned on.

  • digits
    You can set a white list

tessedit_char_whitelist 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
  • hocr

tessedit_create_hocr 1

TestEdit _ Create _ Hocr1, which means to output Html

Use

public static String recognize(String fileName)  {
        BytePointer outText;

        tesseract.TessBaseAPI api = new tesseract.TessBaseAPI();
        String path = OcrUtil.class.getClassLoader().getResource("").getPath();
        if (api.Init(path, "ENG") != 0) {
            System.err.println("Could not initialize tesseract.");
            System.exit(1);
        }

//        api.SetVariable("tessedit_char_whitelist", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
//        api.SetPageSegMode(tesseract.PSM_SINGLE_LINE);

        // Open input image with leptonica library
        lept.PIX image = pixRead(fileName);
        api.SetImage(image);
        // Get OCR result
        outText = api.GetUTF8Text();
        String captcha = outText.getString();
        // Destroy used object and release memory
        api.End();
        outText.deallocate();
        pixDestroy(image);
        api.close();
        return captcha.trim();
    }

doc