1. 程式人生 > >android客戶端ORC圖片識別庫tess_two的使用

android客戶端ORC圖片識別庫tess_two的使用

先導庫

implementation 'com.rmtheis:tess-two:9.0.0'

既然是圖片識別,那一想就可知,需要傳入一個圖片bitmap,那麼返回的肯定是圖片中的內容String。

TessBaseAPI tessBaseAPI = new TessBaseAPI();

tessBaseAPI.init(DATAPATH, DEFAULT_LANGUAGE);

tessBaseAPI.setImage(bitmap);

String text = tessBaseAPI.getUTF8Text();

3行程式碼,就這麼簡單。單身麼,先new個TessBaseAPI物件。  初始化。DATAPATH 和 

DEFAULT_LANGUAGE如下
private static final String DATAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
private static final String DEFAULT_LANGUAGE = "chi_sim";

然後呢,就做這些肯定是會報錯的。我就踩了這個坑。SD卡許可權。別忘了加。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

6.0以上動態申請許可權。你懂的。自己百度去吧。

然後有個copyToSD方法是將assets中的識別庫複製到SD卡中。待會貼上完整程式碼。

assets目錄下需要的檔案在這裡,自己去下。

有很多,我目前只用了

chi_sim.traineddata

eng.traineddata

hebing.traineddata

nor.traineddata

normal.traineddata

這5個,你可以根據需要加到assets下

第三個方法就是設定一個bitmap進去了,然後 tessBaseAPI.getUTF8Text();就可以獲取讀取到的內容了。非常簡單。  貼上完整程式碼

public class Main2Activity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "Main2Activity";
    private Button btn;
    private TextView tv;
    private ImageView cropView;
    /**
     * TessBaseAPI初始化用到的第一個引數,是個目錄。
     */
    private static final String DATAPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
    /**
     * 在DATAPATH中新建這個目錄,TessBaseAPI初始化要求必須有這個目錄。
     */
    private static final String tessdata = DATAPATH + File.separator + "tessdata";
    /**
     * TessBaseAPI初始化測第二個引數,就是識別庫的名字不要字尾名。
     */
    private static final String DEFAULT_LANGUAGE = "chi_sim";
    /**
     * assets中的檔名
     */
    private static final String DEFAULT_LANGUAGE_NAME = DEFAULT_LANGUAGE + ".traineddata";
    /**
     * 儲存到SD卡中的完整檔名
     */
    private static final String LANGUAGE_PATH = tessdata + File.separator + DEFAULT_LANGUAGE_NAME;

    /**
     * 許可權請求值
     */
    private static final int PERMISSION_REQUEST_CODE=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        btn = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);
        cropView = (ImageView) findViewById(R.id.iv);
        Log.d("dddd",DATAPATH);
        btn.setOnClickListener(this);
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
            }
        }

        //Android6.0之前安裝時就能複製,6.0之後要先請求許可權,所以6.0以上的這個方法無用。
        copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i(TAG, "run: kaishi " + System.currentTimeMillis());

                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yinni);
                        Log.i(TAG, "run: bitmap " + System.currentTimeMillis());

                        TessBaseAPI tessBaseAPI = new TessBaseAPI();

                        tessBaseAPI.init(DATAPATH, DEFAULT_LANGUAGE);

                        tessBaseAPI.setImage(bitmap);

                        final String text = tessBaseAPI.getUTF8Text();
                        Log.i(TAG, "run: text " + System.currentTimeMillis() + text);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText(text);
                                Log.d("dddd","識別結果"+text);
                            }
                        });

                        tessBaseAPI.end();
                    }
                }).start();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cropView.setImageDrawable(getResources().getDrawable(R.drawable.yinni));
            }
        });
    }

    /**
     * 將assets中的識別庫複製到SD卡中
     * @param path  要存放在SD卡中的 完整的檔名。這裡是"/storage/emulated/0//tessdata/chi_sim.traineddata"
     * @param name  assets中的檔名 這裡是 "chi_sim.traineddata"
     */
    public void copyToSD(String path, String name) {
        Log.i(TAG, "copyToSD: "+path);
        Log.i(TAG, "copyToSD: "+name);

        //如果存在就刪掉
        File f = new File(path);
        if (f.exists()){
            f.delete();
        }
        if (!f.exists()){
            File p = new File(f.getParent());
            if (!p.exists()){
                p.mkdirs();
            }
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        InputStream is=null;
        OutputStream os=null;
        try {
            is = this.getAssets().open(name);
            File file = new File(path);
            os = new FileOutputStream(file);
            byte[] bytes = new byte[2048];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.btn:
//                break;
//        }
    }
    public boolean checkTraineddataExists(){
        File file = new File(LANGUAGE_PATH);
        return file.exists();
    }
    /**
     * 請求到許可權後在這裡複製識別庫
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.i(TAG, "onRequestPermissionsResult: "+grantResults[0]);
        switch (requestCode){
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    Log.i(TAG, "onRequestPermissionsResult: copy");
                    copyToSD(LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 識別影象
     *
     * @param bitmap
     */
    private void recognition(final Bitmap bitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String text="";
                if (!checkTraineddataExists()){
                    text+=LANGUAGE_PATH+"不存在,開始複製\r\n";
                    Log.i(TAG, "run: "+LANGUAGE_PATH+"不存在,開始複製\r\n");
                    assets2SD(getApplicationContext(), LANGUAGE_PATH, DEFAULT_LANGUAGE_NAME);
                }
                text+=LANGUAGE_PATH+"已經存在,開始識別\r\n";
                Log.i(TAG, "run: "+LANGUAGE_PATH+"已經存在,開始識別\r\n");
                long startTime = System.currentTimeMillis();
                Log.i(TAG, "run: kaishi " + startTime);
                TessBaseAPI tessBaseAPI = new TessBaseAPI();
                tessBaseAPI.init(DATAPATH, DEFAULT_LANGUAGE);
                tessBaseAPI.setImage(bitmap);
                text =text+"識別結果:"+ tessBaseAPI.getUTF8Text();
                long finishTime = System.currentTimeMillis();
                Log.i(TAG, "run: jieshu " + finishTime);
                Log.i(TAG, "run: text " + text);
                text = text + "\r\n" + " 耗時" + (finishTime - startTime) + "毫秒";
                final String finalText = text;
                final Bitmap finalBitmap = bitmap;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(finalText);
                        cropView.setImageBitmap(finalBitmap);
                    }
                });
                tessBaseAPI.end();
            }
        }).start();
    }
}