Android

Introduction

In this tutorial, we will learn how to do Optical Character Recognition with a Camera in Android using Vision API. Here, we will just import the Google Vision API Library with Android Studio and implement the OCR for retrieving text from the camera preview.
You can find my previous tutorial on Optical Character Recognition using Google Vision API for Recognizing Text from Images here. My previous tutorial covered the introduction of Google Vision API. Therefore, without any delay, we will skip the coding part.
Steps
I have split this part into four steps as in the following.
Step 1 - Creating a New Project with Empty Activity and Gradle Setup
We will start coding for OCR. Create a New Android Project. Add the following line in your app level build.gradle file to import the library.
implementation 'com.google.android.gms:play-services-vision:15.2.0'
Step 2 - Setting up Manifest for OCR
Open your manifest file and add the following code block to instruct the app to install or download the dependencies at the time of installing the app.
  1. <meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="ocr"/>
Step 3 - Implementing Camera View using SurfaceView
Open your activity_main.xml file and paste the following code. It's just the designer part of the application.
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="com.androidmads.ocrcamera.MainActivity">
  8. <SurfaceView
  9. android:id="@+id/surface_view"
  10. android:layout_width="match_parent"
  11. android:layout_height="match_parent" />
  12. <TextView
  13. android:id="@+id/txtview"
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content"
  16. app:layout_constraintBottom_toBottomOf="parent"
  17. android:text="No Text"
  18. android:textColor="@android:color/white"
  19. android:textSize="20sp"
  20. android:padding="5dp"/>
  21. </android.support.constraint.ConstraintLayout>
Step 4 - Implementing OCR in Application
Open your MainActivity.java file and initialize the widget used in your designer. Add the following code to start Camera View.
Implement your Activity with SurfaceHolder.Callback, Detector Processor to start your camera preview.
  1. TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
  2. if (!txtRecognizer.isOperational()) {
  3. Log.e("Main Activity", "Detector dependencies are not yet available");
  4. } else {
  5. cameraSource = new CameraSource.Builder(getApplicationContext(), txtRecognizer)
  6. .setFacing(CameraSource.CAMERA_FACING_BACK)
  7. .setRequestedPreviewSize(1280, 1024)
  8. .setRequestedFps(2.0f)
  9. .setAutoFocusEnabled(true)
  10. .build();
  11. cameraView.getHolder().addCallback(this);
  12. txtRecognizer.setProcessor(this);
  13. }
Here, TextRecognizer is used to do Character Recognition in Camera Preview & txtRecognizer.isOperational() is used to check if the device has the support for Google Vision API. The output of the TextRecognizer can be retrieved by using SparseArray and StringBuilder.

TextBlock

I have used TextBlock to retrieve the paragraph from the image using OCR.

Lines

You can get the line from the TextBlock using
textblockName.getComponents()

Element

You can get the line from the TextBlock using
lineName.getComponents()
Camera Source istarts on the surface created with callback and does the scanning process. The Received Detections are read by SparseArray and are similar to reading data with a bitmap in android.
The Text View at the bottom of the screen is used to preview the scanned data.
full code
You can find the full code here.
  1. public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, Detector.Processor {
  2. private SurfaceView cameraView;
  3. private TextView txtView;
  4. private CameraSource cameraSource;
  5. @SuppressLint("MissingPermission")
  6. @Override
  7. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  8. switch (requestCode) {
  9. case 1: {
  10. if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  11. try {
  12. cameraSource.start(cameraView.getHolder());
  13. } catch (Exception e) {
  14. }
  15. }
  16. }
  17. break;
  18. }
  19. }
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_main);
  24. cameraView = findViewById(R.id.surface_view);
  25. txtView = findViewById(R.id.txtview);
  26. TextRecognizer txtRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
  27. if (!txtRecognizer.isOperational()) {
  28. Log.e("Main Activity", "Detector dependencies are not yet available");
  29. } else {
  30. cameraSource = new CameraSource.Builder(getApplicationContext(), txtRecognizer)
  31. .setFacing(CameraSource.CAMERA_FACING_BACK)
  32. .setRequestedPreviewSize(1280, 1024)
  33. .setRequestedFps(2.0f)
  34. .setAutoFocusEnabled(true)
  35. .build();
  36. cameraView.getHolder().addCallback(this);
  37. txtRecognizer.setProcessor(this);
  38. }
  39. }
  40. @Override
  41. public void surfaceCreated(SurfaceHolder holder) {
  42. try {
  43. if (ActivityCompat.checkSelfPermission(this,
  44. Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
  45. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},1);
  46. return;
  47. }
  48. cameraSource.start(cameraView.getHolder());
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. @Override
  54. public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  55. }
  56. @Override
  57. public void surfaceDestroyed(SurfaceHolder holder) {
  58. cameraSource.stop();
  59. }
  60. @Override
  61. public void release() {
  62. }
  63. @Override
  64. public void receiveDetections(Detector.Detections detections) {
  65. SparseArray items = detections.getDetectedItems();
  66. final StringBuilder strBuilder = new StringBuilder();
  67. for (int i = 0; i < items.size(); i++)
  68. {
  69. TextBlock item = (TextBlock)items.valueAt(i);
  70. strBuilder.append(item.getValue());
  71. strBuilder.append("/");
  72. // The following Process is used to show how to use lines & elements as well
  73. for (int j = 0; j < items.size(); j++) {
  74. TextBlock textBlock = (TextBlock) items.valueAt(j);
  75. strBuilder.append(textBlock.getValue());
  76. strBuilder.append("/");
  77. for (Text line : textBlock.getComponents()) {
  78. //extract scanned text lines here
  79. Log.v("lines", line.getValue());
  80. strBuilder.append(line.getValue());
  81. strBuilder.append("/");
  82. for (Text element : line.getComponents()) {
  83. //extract scanned text words here
  84. Log.v("element", element.getValue());
  85. strBuilder.append(element.getValue());
  86. }
  87. }
  88. }
  89. }
  90. Log.v("strBuilder.toString()", strBuilder.toString());
  91. txtView.post(new Runnable() {
  92. @Override
  93. public void run() {
  94. txtView.setText(strBuilder.toString());
  95. }
  96. });
  97. }
  98. }
Download Code
You can download the full source code for this article from GitHub.