Android - использование библиотеки OCR Tess-two на пушту - PullRequest
0 голосов
/ 05 мая 2020

Я использовал библиотеку tess-two tesseract ocr в моем android проекте, она дает мне результат, но результат не подходит. это мой код, который я сделал для своего проекта Этот код копирует данные tess из каталога ресурсов во внешний каталог устройства во время установки. Класс Myapplication для данных tess

package com.smartechafghanistan.com.tesseractexample;
import android.app.Application;
import android.content.res.AssetManager;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Instant;
public class MainApplication extends Application {
    public static MainApplication instance=null;
    @Override
    public void onCreate() {
        super.onCreate();
        copyTessDataForTextRecognizer();
        instance=this;
    }
    private String tessDataPath(){
        return MainApplication.instance.getExternalFilesDir(null)+"/tessdata/";
    }
    public String getTessParentDirectory(){
        return MainApplication.instance.getExternalFilesDir(null).getAbsolutePath();
    }


    private  void copyTessDataForTextRecognizer(){

        Runnable run=new Runnable() {
            @Override
            public void run() {
                AssetManager assetManager=MainApplication.instance.getAssets();
                OutputStream out=null;

                try {

                    InputStream in=assetManager.open("fas.traineddata");
                    String tesspath= instance.tessDataPath();
                    File teeFolder=new File(tesspath);
                    if(!teeFolder.exists()){
                        teeFolder.mkdir();
                    }
                    String tessdata=tesspath+"/"+"fas.traineddata";
                    File tessfile=new File(tessdata);
                    if(!tessfile.exists()){
                        out=new FileOutputStream(tessdata);
                        byte []buffer=new byte[1024];
                        int read=in.read(buffer);

                        while (read !=-1){
                            out.write(buffer,0,read);
                            read=in.read(buffer);


                        }
                    }
                    else {
                        Toast.makeText(getApplicationContext(),"error in else",Toast.LENGTH_SHORT).show();
                    }

                }catch (Exception e){

                }
                finally {
                    try{
                        if(out!=null){
                            out.close();
                        }

                    }catch (Exception e){
                        Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                    }
                }

            }
        };
        new Thread(run).start();



    }
}

это класс MainActivity Этот код предназначен для захвата изображения с камеры или получения изображения из галереи

package com.smartechafghanistan.com.tesseractexample;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.provider.MediaStore;
import android.speech.tts.TextToSpeech;
import android.util.SparseArray;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final int CAMERA_REQUEST_CODE = 200;
    private static final int STORAGE_REQUEST_CODE = 400;
    private static final int IMAGE_PICK_GALLERY_CODE = 1000;
    private static final int IMAGE_PICK_CAMERA_CODE = 1001;
    String camerapermission[];
    String storagepermission[];
    ImageButton btnword;

    TextToSpeech textToSpeech;

    Uri image_uri;
    EditText mresult;
    ImageView imageView;
    OCRClass ocrClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ocrClass = new OCRClass();

        mresult = (EditText) findViewById(R.id.edresult);
        imageView = (ImageView) findViewById(R.id.imageshow);
        btnword=(ImageButton)findViewById(R.id.btncreateword);
        btnword.setVisibility(View.INVISIBLE);


        camerapermission=new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        storagepermission=new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};


        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void getcamera(View view) {

        String [] items={"Camera","Gallery"};
        AlertDialog.Builder dialog=new AlertDialog.Builder(this);
        dialog.setTitle("Select Image");
        dialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if(which==0){
                    Toast.makeText(getApplicationContext(),"Camera",Toast.LENGTH_LONG).show();


                    if(!checkCameraPermission()){

                        requestCameraPermission();

                    }
                    else{
                        pickCamera();
                    }

                }
                if(which==1){
                    Toast.makeText(getApplicationContext(),"Gallery",Toast.LENGTH_LONG).show();

                    if(!checkStoragePermission()){

                        requestStoragePermission();

                    }
                    else{
                        pickStorage();
                    }

                }

            }
        });

        dialog.create().show();


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_REQUEST_CODE:

                if (grantResults.length > 0) {
                    boolean cameracepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                    boolean writestorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameracepted && writestorageaccepted) {
                        pickCamera();
                    } else {
                        Toast.makeText(getApplicationContext(), "permission denied", Toast.LENGTH_LONG).show();
                    }
                }
                break;


            case STORAGE_REQUEST_CODE:

                if (grantResults.length > 0) {

                    boolean writestorageaccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (writestorageaccepted) {
                        pickStorage();
                    } else {
                        Toast.makeText(getApplicationContext(), "permission denied", Toast.LENGTH_LONG).show();
                    }
                }
                break;

        }
    }

    private void requestStoragePermission() {


        ActivityCompat.requestPermissions(this, storagepermission, STORAGE_REQUEST_CODE);

    }


    private boolean checkStoragePermission() {
        boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);

        return result;

    }

    private void requestCameraPermission() {
        ActivityCompat.requestPermissions(this, camerapermission, CAMERA_REQUEST_CODE);
    }

    private boolean checkCameraPermission() {
        boolean result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);

        boolean result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);

        return result & result1;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (resultCode == RESULT_OK) {
            if (requestCode == IMAGE_PICK_GALLERY_CODE) {
                Toast.makeText(getApplicationContext(), " on activiyt result gallerry", Toast.LENGTH_LONG).show();
                CropImage.activity(data.getData()).setGuidelines(CropImageView.Guidelines.ON).start(this);
               // CropImage.activity();


            }
            if (requestCode == IMAGE_PICK_CAMERA_CODE) {
                Toast.makeText(getApplicationContext(), " on activiyt result camera", Toast.LENGTH_LONG).show();

                CropImage.activity(image_uri).setGuidelines(CropImageView.Guidelines.ON).start(this);

            }
        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {

            CropImage.ActivityResult result = CropImage.getActivityResult(data);

            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                imageView.setImageURI(resultUri);

                BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
                Bitmap bitmap = bitmapDrawable.getBitmap();
                String resulttxt = ocrClass.InitOcr(bitmap);
                mresult.setText(resulttxt);

            }
            else  if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){

                Exception error=result.getError();
                Toast.makeText(getApplicationContext(),""+error,Toast.LENGTH_LONG).show();

            }
        }

    }

    public  void CopytoClipboard(View view){
        String mdata=mresult.getText().toString();
        if(!mdata.equals(null)) {
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("Text", mresult.getText().toString());
            clipboardManager.setPrimaryClip(clipData);
            Toast.makeText(getApplicationContext(),"data copied to clipboad",Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(getApplicationContext(),"Edit text is empty",Toast.LENGTH_LONG).show();
        }
    }

    public void CreateNewFile(View view) {



    }

    public void ConverTextToSpeach(View view) {
        textToSpeech.speak(mresult.getText().toString(), TextToSpeech.QUEUE_FLUSH,null);
        Toast.makeText(getApplicationContext(),"This function is working fine",Toast.LENGTH_LONG).show();


    }

    public void SharewithWord(View view) {
        Intent intentword=getPackageManager().getLaunchIntentForPackage("com.gamil.heagoo.apkeditor");
        startActivity(intentword);
    }
    public void shareAndIndesterial(View view) {



            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            String finalMsg = String.valueOf(mresult.getText().toString().trim());
            intent.putExtra(Intent.EXTRA_TEXT, finalMsg);
            Intent modIntent = Intent.createChooser(intent, "Send With..");
            startActivity(modIntent);
        }





    private void pickCamera() {
        ContentValues contentValues=new ContentValues();
        contentValues.put(MediaStore.Images.Media.TITLE,"new Image");
        contentValues.put(MediaStore.Images.Media.DESCRIPTION,"Image to text");
        image_uri=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);

        Intent cameraIntent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,image_uri);
        startActivityForResult(cameraIntent,IMAGE_PICK_CAMERA_CODE);





    }

    private void pickStorage() {
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent,IMAGE_PICK_GALLERY_CODE);

    }

}

это класс ocr Извлечение текста из изображения отвечает класс ocr

package com.smartechafghanistan.com.tesseractexample;

import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.googlecode.tesseract.android.TessBaseAPI;

public class OCRClass {

       public String InitOcr( Bitmap bitmap){
        TessBaseAPI tessBaseAPI=new TessBaseAPI();
        String datpath=MainApplication.instance.getTessParentDirectory();
        tessBaseAPI.init(datpath,"fas");
        tessBaseAPI.setImage(bitmap);

           String result="no result";

           try{
               result=tessBaseAPI.getUTF8Text();


           }catch ( Exception e){
               Log.d("error ","eroor imn processing ocr");
           }
           tessBaseAPI.end();
           return result;
    }

//    public void doOCR(){
//        TessBaseAPI tessBaseAPI=new TessBaseAPI();
//        String datpath=MainApplication.instance.getTessParentDirectory();
//        tessBaseAPI.init(datpath,"eng");
//    }


}
...