如何从OCR应用程序中提取特定单词

时间:2019-12-27 12:15:37

标签: android android-studio ocr

问候,我正在android studio中进行OCR工作,但是我需要,例如,如果我为一张发票拍照,则只能检测到文档ID(序列号)中特定的单词。

当前,该应用程序允许您抛出照片或搜索图库,然后剪切文档的一部分并将其粘贴到EditText中。

代码:

public class MainActivity extends AppCompatActivity {

EditText mResultEt;
ImageView mPreviewIv;

private static final int CAMERA_REQUEST_CODE = 1000;
private static final int STORAGE_REQUEST_CODE = 1400;
private static final int IMAGE_PICK_GALLERY_CODE = 2000;
private static final int IMAGE_PICK_CAMERA_CODE = 2001;


String cameraPermission[];
String storagePermission[];

Uri image_uri;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setSubtitle("Click + button to inter Image");

    mResultEt = findViewById(R.id.resultEt);
    mPreviewIv = findViewById(R.id.imageIv);


    //camera permission
    cameraPermission =  new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    //storage permission
    storagePermission =  new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE};
}



//Actionbar menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    //inflate menu
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}


//handle actionbar item clicks
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.addImage){
        showImageImportDialog();
    }
    /*if (id == R.id.settings){
        Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
    }*/
    return super.onOptionsItemSelected(item);
}

private void showImageImportDialog() {
    //items to display in dialog
    String[] items = {"Camera", "Gallery"};
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    //set title
    dialog.setTitle("Select Image");
    dialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which == 0){
                //camera option clicked
                if (!checkCameraPermission()){
                    //camera permission not allowed, request it
                    requestCameraPermission();
                }
                else{
                    //permission allowed, take picture
                    pickCamera();
                }
            }

            if (which == 1){
                //gallery option clicked
                if(!checkStoragePermission()){
                    //Storage permission not allowed, request it
                    requestStoragePermission();
                }
                else{
                    //permission allowed, take picture
                    pickGallery();
                }
            }
        }
    });
    dialog.create().show();// show dialog
}

private void pickGallery() {
    //intent to pick image from gallery
    Intent intent = new Intent(Intent.ACTION_PICK);
    //set intent type to image
    intent.setType("image/*");
    startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}

private void pickCamera() {
    //intent to take image from camera, it will also be save to storage to get high quality image
    ContentValues values =  new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, "NewPic"); //tittle of the picture
    values.put(MediaStore.Images.Media.DESCRIPTION, "Image To text"); // description
    image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

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

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() {
    //Check camera permission and return the result in order to get high quality image we have to save image to external storage first
    // before inserting to image view that's why storage permission will also be required
    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;

}

//handle permission result


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

    switch (requestCode){
        case CAMERA_REQUEST_CODE:
            if(grantResults.length >0){
                boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean writeStorageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if(cameraAccepted && writeStorageAccepted){
                    pickCamera();
                }
                else{
                    Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
                }
            }
            break;
        case STORAGE_REQUEST_CODE:
            if(grantResults.length >0){
                boolean writeStorageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if(writeStorageAccepted){
                    pickGallery();
                }
                else{
                    Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
                }
            }
            break;

    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (resultCode == RESULT_OK){
        if (requestCode == IMAGE_PICK_GALLERY_CODE){
            //got image from gallery now crop it
            CropImage.activity(data.getData()).setGuidelines(CropImageView.Guidelines.ON).start(this);

        }
        if (requestCode ==  IMAGE_PICK_CAMERA_CODE){
            // got image from camera now crop it
            CropImage.activity(image_uri)
                    .setGuidelines(CropImageView.Guidelines.ON)// enable image guidlines
                    .start(this);
        }
    }
    //get cropped image
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK){
            Uri resultUri = result.getUri(); //get image uri
            //set image to image view
            mPreviewIv.setImageURI(resultUri);


            //get drawable bitmap for text recognition
            BitmapDrawable bitmapDrawable = (BitmapDrawable)mPreviewIv.getDrawable();
            Bitmap bitmap = bitmapDrawable.getBitmap();

            TextRecognizer recognizer = new TextRecognizer.Builder(getApplicationContext()).build();

            if (!recognizer.isOperational()){
                Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
            }
            else{
                Frame frame = new Frame.Builder().setBitmap(bitmap).build();
                SparseArray<TextBlock> items = recognizer.detect(frame);
                StringBuilder sb = new StringBuilder();
                //get text from sb until there is no text
                for (int i = 0; i < items.size(); i++){
                    TextBlock myItem =  items.valueAt(i);
                    sb.append(myItem.getValue());
                    sb.append("\n\n");

                }
                //set text to edit text
                mResultEt.setText(sb.toString());
            }
        }

    }

}

}

0 个答案:

没有答案