Ocr.java 2.55 KB
Newer Older
limm's avatar
limm committed
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import mmdeploy.TextDetector;
import mmdeploy.TextRecognizer;
import mmdeploy.PixelFormat;
import mmdeploy.DataType;
import mmdeploy.Mat;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;
import java.io.IOException;

/** @description: this is a class for Ocr java demo. */
public class Ocr {

    /** The main function for Ocr Java demo.
     * @param deviceName: the device name of the demo.
     * @param detModelPath: the text detection model path.
     * @param recModelPath: the text recognition model path.
     * @param imagePath: the image path.
     */
    public static void main(String[] args) {
        // Parse arguments
        if (args.length != 4) {
            System.out.println("usage:\njava Ocr deviceName detModelPath recModelPath imagePath");
            return;
        }
        String deviceName = args[0];
        String detModelPath = args[1];
        String recModelPath = args[2];
        String imagePath = args[3];

        // create text detector and recognizer
        TextDetector text_detector = null;
        TextRecognizer text_recognizer = null;

        try {
            text_detector = new TextDetector(detModelPath, deviceName, 0);
            text_recognizer = new TextRecognizer(recModelPath, deviceName, 0);

            // load image
            Mat img = Utils.loadImage(imagePath);

            // apply text detector
            TextDetector.Result[] detResult = text_detector.apply(img);

            int [] detResultCount = {detResult.length};
            TextRecognizer.Result[] recResult = text_recognizer.applyBbox(img, detResult, detResultCount);
            if (recResult == null) {
                System.out.println("Apply TextRecognizer failed.");
                System.exit(1);
            }
            // print results
            for (int i = 0; i < detResultCount[0]; ++i) {
                System.out.printf("box[%d]: %s\n", i, new String(recResult[i].text));
                for (int j = 0; j < 4; ++j) {
                    System.out.printf("x: %.2f, y: %.2f, ", detResult[i].bbox[j].x, detResult[i].bbox[j].y);
                }
                System.out.printf("\n");
            }
        } catch (Exception e) {
            System.out.println("exception: " + e.getMessage());
        } finally {
            // release text detector and recognizer
            if (text_recognizer != null) {
                text_recognizer.release();
            }
            if (text_detector != null) {
                text_detector.release();
            }
        }
    }
}