无法从从图库中选择的图像中提取文本

时间:2018-10-04 13:23:15

标签: android android-studio ocr tesseract

下面是我的代码,我可以用捕获的图像完美地提取文本,但是我无法使用从移动图库中选择的图像来提取文本。就像我通过该应用程序单击图片一样,我可以提取文本,但是如果我从图库中选择图片,则不能。对于选定的图像,我能够获取图像的路径,但是随后,我不知道为什么tesseract方法不起作用。请帮我解决这个问题。

public class HomeActivity extends AppCompatActivity  {

public static final String TESS_DATA = "/tessdata";
private static final String TAG = MainActivity.class.getSimpleName();
private static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/Tess";
private TextView textView;
private TessBaseAPI tessBaseAPI;
private Uri outputFileDir;
private String mCurrentPhotoPath;
private static final int PICK_IMAGE= 100;
Button btnSpeak;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    textView = (TextView) this.findViewById(R.id.textView);
    btnSpeak=(Button)this.findViewById(R.id.btnSpeak);

    final Activity activity = this;
    checkPermission();
    this.findViewById(R.id.btnCamera).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkPermission();
            dispatchTakePictureIntent();
        }
    });
    this.findViewById(R.id.btnUpload).setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
            openGallery();
        }
    });
}

private void checkPermission() {
    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 120);
    }
    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 121);
    }
}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this,
                    BuildConfig.APPLICATION_ID + ".provider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, 1024);
        }
    }
}
public void openGallery(){
    Intent gallery=new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    startActivityForResult(gallery,PICK_IMAGE);

}


private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    return image;
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1024) {
        if (resultCode == Activity.RESULT_OK) {
            prepareTessData();
            startOCR(outputFileDir);
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Result canceled.", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Activity result failed.", Toast.LENGTH_SHORT).show();
        }
    }
    else if( requestCode==Activity.RESULT_OK &&requestCode==PICK_IMAGE )
    {

            Uri ImageUri = data.getData();
            mCurrentPhotoPath = getRealPathFromURI(ImageUri);
            Toast.makeText(getApplicationContext(), mCurrentPhotoPath, Toast.LENGTH_LONG).show();
           prepareTessData();
            startOCR(outputFileDir);

         if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Result canceled.", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Activity result failed.", Toast.LENGTH_SHORT).show();
        }
    }

}

public String getRealPathFromURI(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

private void prepareTessData(){
    try{
        File dir = getExternalFilesDir(TESS_DATA);
        if(!dir.exists()){
            if (!dir.mkdir()) {
                Toast.makeText(getApplicationContext(), "The folder " + dir.getPath() + "was not created", Toast.LENGTH_SHORT).show();
            }
        }
        String fileList[] = getAssets().list("");
        for(String fileName : fileList){
            String pathToDataFile = dir + "/" + fileName;
            if(!(new File(pathToDataFile)).exists()){
                InputStream in = getAssets().open(fileName);
                OutputStream out = new FileOutputStream(pathToDataFile);
                byte [] buff = new byte[1024];
                int len ;
                while(( len = in.read(buff)) > 0){
                    out.write(buff,0,len);
                }
                in.close();
                out.close();
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}

private void startOCR(Uri imageUri){
    try{
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = 10;
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);

        String result = this.getText(bitmap);
        textView.setText(result);
    }catch (Exception e){
        Log.e(TAG, e.getMessage());
    }
}

private String getText(Bitmap bitmap){
    try{
        tessBaseAPI = new TessBaseAPI();
    }catch (Exception e){
        Log.e(TAG, e.getMessage());
    }
    String dataPath = getExternalFilesDir("/").getPath() + "/";
    tessBaseAPI.init(dataPath, "eng");
    tessBaseAPI.setImage(bitmap);
    String retStr = "No result";
    try{
        retStr = tessBaseAPI.getUTF8Text();
    }catch (Exception e){
        Log.e(TAG, e.getMessage());
    }
    tessBaseAPI.end();
    return retStr;
}

}

0 个答案:

没有答案