android - 如何拍照然后使用 TextRecognizer 读取其文本

标签 android bitmap decode

所以我有这个按钮来拍照包含文字:

 takePic.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {

         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
         startActivityForResult(intent,100);
     }
 });

然后我从 onActivityResult 获取图像:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == 100) {
        Bitmap bitmap = (Bitmap) data.getExtras().get("data");

    }
}

现在的问题是,当我将此位图传递给 textRecognizer 检测器时,我没有得到任何结果:

Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
textRecognizer = new TextRecognizer.Builder(this).build();

SparseArray<TextBlock> item = textRecognizer.detect(frame);

如果图像存储在 drawable 文件夹中我可以很容易地做到这一点:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.myImage);

我很乐意使用 TextRecognizer ..

但我不知道如何处理相机拍摄的图像。

编辑:

完整示例:

public class MainActivity extends AppCompatActivity {


    private TextRecognizer textRecognizer;
    private ImageView imageView;
    private TextView Result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView);
        Result = findViewById(R.id.tvResult);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.image);

        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
        textRecognizer = new TextRecognizer.Builder(this).build();

        SparseArray<TextBlock> item = textRecognizer.detect(frame);

        StringBuilder stringBuilder = new StringBuilder();

        for (int i=0; i<item.size(); i++){

            stringBuilder.append(item.valueAt(i).getValue());


        } 
   Result.setText(stringBuilder.toString());

    }

}

activity_main.xml:

 <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/image" />

    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="96dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:text="result"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

最佳答案

最好给camera intent一个文件,这样它就帮你保存了文件。

根据 This Answer :

private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

关于android - 如何拍照然后使用 TextRecognizer 读取其文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49314353/

相关文章:

java - 如何将 Java 中的 URI 解析和解码为 URI 组件?

android - notifyDataSetChanged 从不工作

android - Flutter 中的 OAuth2 身份验证

android - 仅在 1 个用户中出现奇怪的异常

Android,将位图绘制到 Canvas 的最快方法

android - 如何解决Android中的java.lang.OutOfMemoryError故障

android - 将位图存储为临时文件以实现撤消和重做功能是个好主意吗?

python - 读取文本文件的行并获取字符映射解码错误

android - 在 iOS 的 ReactJS 中显示十进制键盘

python - 如何捕获包含在 boost python 模块中的 C++ 代码中抛出的 Python 异常