Android上图片文字识别

1,358 阅读1分钟

前言

在这里插入图片描述

  OCR 是 Optical Character Recognition 的缩写,翻译为光学字符识别,指的是针对印刷体字符,采用光学的方式将纸质文档中的文字转换成为黑白点阵的图像文件,通过识别软件将图像中的文字转换成文本格式,供文字处理软件进一步编辑加工的技术(好吧,这是我查来的)。简单的来说,OCR技术就是可以把图片上的文字识别出来,并以文本格式的形式提取出来。

  这个技术的应用方面很广泛,比如说把纸质书籍的内容转化为电子书,之前都需要人手打,但是现在只要扫描一下,将扫描出来的图片通过OCR技术转化成文本格式,效率和成本不知提升了多少倍。

可运行的步骤

1、添加依赖

implementation "com.rmtheis:tess-two:8.0.0"

2、下载字体识别库(chi_sim.traineddata 中文简体,chi_tra.traineddata 中文繁体,eng.traineddata 英文库)

3、为了apk的大小,我们需要将字体识别库文件拷贝到SD卡目录中,比如eng.traineddata的copy

private String mDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
private String mFilePath = mDataPath + File.separator + "tessdata" + File.separator + "eng.traineddata";
private void copyFile() {
        try {
            File mFile = new File(mFilePath);
            if (mFile.exists()) {
                mFile.delete();
            }
            if (!mFile.exists()) {
                File p = new File(mFile.getParent());
                if (!p.exists()) {
                    p.mkdirs();
                }
                try {
                    mFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            OutputStream os = new FileOutputStream(mFilePath);
            InputStream is = this.getAssets().open("eng.traineddata");
            byte\[\] buffer = new byte\[1024\];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4、tess two初始化

TessBaseAPI baseApi;
baseApi = new TessBaseAPI();
baseApi.init(mDataPath, "eng");

5、处理bitmap图片并识别里面的内容

//OCR图片文字识别
baseApi.setImage(bitmap);
String result = baseApi.getUTF8Text().replace(" ", "").toLowerCase();

到此,关于“Android如何实现图片文字识别”的学习就结束了,希望能够解决大家的疑惑。