当前位置:   article > 正文

Android 开发 OCR 拍照 + ML Kit 识别文字 巨详细全部代码教程_android ocr

android ocr

效果图

  • 流程:点击拍照,调取设备相机拍照,获取图片显示到页面,提取照片内的文字
    在这里插入图片描述

一、OCR的含义

ocr是Optical Character Recognition(光学字符识别)是指电子设备(例如扫描仪或数码相机)检查纸上打印的字符,通过检测暗、亮的模式确定其形状,然后用字符识别方法将形状翻译成计算机文字的过程

二、什么是ML Kit

ML Kit是一个由Google开发的跨平台移动SDK(Android和iOS)。它带来了谷歌的端上机器学习能力。
ML Kit所有在端上运行的API允许实时和离线功能。这也意味着这些功能在离线模式下也可用。

ML Kit可以识别超过100种语言的文本,包括原生拼写及罗马转写系统,比如汉语、俄语、印地语、英语、希腊语等。点击查看支持语言的完整列表

三、官网步骤教程

  • 本文跟着官网教程走,如下图:
    在这里插入图片描述

1、添加依赖

注意此 API 需要 Android API 级别 21 或更高版本。确保应用的 build file 使用值 21 或更高。minSdkVersion

  • 在项目级文件中,请确保在 your 和 sections 中都包含 GoogleMaven 存储库。build.gradlebuildscriptallprojects
  • 将 ML Kit Android 库的依赖项添加到模块的应用级 gradle 文件,该文件通常为:app/build.gradle

本文讲的是中文识别,所以只导入了中文依赖包,你可以根据自己所需选择导入的依赖包

 // To recognize Chinese script
  implementation 'com.google.mlkit:text-recognition-chinese:16.0.0'
  • 1
  • 2

在这里插入图片描述

2、创建TextRecognizer

因为本文是中文,所以使用的中文脚本库

 ChineseTextRecognizerOptions build = new ChineseTextRecognizerOptions.Builder().build();
 TextRecognizer recognizer = TextRecognition.getClient(build);
  • 1
  • 2

在这里插入图片描述

3、输入图像

图像来源有:

  • 使用media.Image
  • 使用文件 URI
  • 使用 或ByteBufferByteArray
  • 使用Bitmap

本文用的是使用Bitmap,如下图

InputImage image = InputImage.fromBitmap(bitmap, 0);
  • 1

在这里插入图片描述

4、处理图像

将图像传递给方法:process

 recognizer.process(image)
                .addOnSuccessListener(new OnSuccessListener<Text>() {
                    @Override
                    public void onSuccess(Text visionText) {
                        // Task completed successfully
                        // ...
                    }
                })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                // Task failed with an exception
                                // ...
                            }
                        });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在这里插入图片描述

四、实际代码案例Demo如下:

别忘了导入依赖包!!!

1、Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/btn"
        android:text="拍照"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

1、Main.java

package com.example.mlkitapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognition;
import com.google.mlkit.vision.text.TextRecognizer;
import com.google.mlkit.vision.text.chinese.ChineseTextRecognizerOptions;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private TextView tv_result;
    private ImageView image;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_result=findViewById(R.id.tv_result);
        image=findViewById(R.id.image);
        //权限检查
        requestCameraPermission();
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) Button btn=findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakePictureIntent();//调本地相机
            }
        });
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    private void requestCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            image.setImageBitmap(imageBitmap);
            // 在这里使用imageBitmap进行文字识别
            recognizeTextFromBitmap(imageBitmap);
        }
    }

    private void recognizeTextFromBitmap(Bitmap bitmap) {
        InputImage image = InputImage.fromBitmap(bitmap, 0);
        ChineseTextRecognizerOptions build = new ChineseTextRecognizerOptions.Builder().build();
        TextRecognizer recognizer = TextRecognition.getClient(build);
        recognizer.process(image)
                .addOnSuccessListener(new OnSuccessListener<Text>() {
                    @Override
                    public void onSuccess(com.google.mlkit.vision.text.Text text) {
                        String text1 = text.getText();
                        tv_result.setText(text1);
                        recognizer.close();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        // 处理错误
                        e.printStackTrace();
                        // 释放资源
                        recognizer.close();
                    }
                });
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/771288
推荐阅读
相关标签
  

闽ICP备14008679号