Android Studio实现文字识别
时间: 2023-11-21 21:58:33 浏览: 194
以下是Android Studio实现文字识别的步骤:
1.在项目的build.gradle文件中添加以下依赖项:
```gradle
dependencies {
// ...
implementation 'com.google.android.gms:play-services-vision:20.1.3'
}
```
2.在布局文件中添加一个SurfaceView和一个TextView:
```xml
<SurfaceView
android:id="@+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#80000000"
android:padding="16dp"
android:textColor="#fff"
android:textSize="18sp" />
```
3.在MainActivity.java文件中添加以下代码:
```java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.Text;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final String TAG = "MainActivity";
private static final int REQUEST_CAMERA_PERMISSION = 200;
private static final int REQUEST_IMAGE_CAPTURE = 1;
private SurfaceView mCameraPreview;
private TextView mTextView;
private TextRecognizer mTextRecognizer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCameraPreview = findViewById(R.id.camera_preview);
mTextView = findViewById(R.id.text_view);
// 检查相机权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
} else {
startCamera();
}
// 初始化文字识别器
mTextRecognizer = new TextRecognizer.Builder(this).build();
if (!mTextRecognizer.isOperational()) {
Log.w(TAG, "Detector dependencies are not yet available.");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 释放文字识别器
mTextRecognizer.release();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// 相机预览开始
startCameraPreview(holder);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// 相机预览变化
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// 相机预览结束
}
private void startCamera() {
SurfaceHolder holder = mCameraPreview.getHolder();
holder.addCallback(this);
}
private void startCameraPreview(SurfaceHolder holder) {
try {
// 打开相机
Camera camera = Camera.open();
camera.setPreviewDisplay(holder);
camera.startPreview();
// 设置相机预览回调
camera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
// 处理相机预览数据
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
detectText(bitmap);
}
});
} catch (IOException e) {
Log.e(TAG, "Error setting camera preview: " + e.getMessage());
}
}
private void detectText(Bitmap bitmap) {
// 创建帧
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
// 获取文本块
SparseArray<TextBlock> textBlocks = mTextRecognizer.detect(frame);
// 处理文本块
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < textBlocks.size(); i++) {
TextBlock textBlock = textBlocks.valueAt(i);
for (Text text : textBlock.getComponents()) {
stringBuilder.append(text.getValue());
stringBuilder.append("\n");
}
}
// 显示识别结果
mTextView.setText(stringBuilder.toString());
}
public void takePicture(View view) {
// 拍照
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
@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 bitmap = (Bitmap) extras.get("data");
detectText(bitmap);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_CAMERA_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
```
4.在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
5.运行应用程序并测试文字识别功能。
阅读全文