安卓:如何提高由Tesseract OCR解析得到的图像数字质量?

12

我制作了一个简单的应用程序,它可以读取图像并将数字图像作为文本检索,该应用程序使用Android。但问题是准确率只有大约60%,而且一些不需要的噪点也会显示出来。我知道准确率不能达到100%,但我相信一定有方法可以改进。但由于我是业余爱好者,所以我发现很难实现。我在谷歌上搜索了许多信息,但仍然没有得到实质性的信息。

我想从如下图片所示的东方幸运彩票中读取596、00和012345这些数字。

输入图像描述


你是否正在使用最新的语言包(3.02)?https://code.google.com/p/tesseract-ocr/downloads/detail?name=tesseract-ocr-3.02.eng.tar.gz&can=2&q=. 同时,请确保拍摄的相机图像质量高。尽量减少位图下采样。 - Abhishek V
是的,当前正在使用的包是最新版本。 - Jennifer
我使用的设备是Nexus 5,所以我相信相机的像素不会太差...但也许不会太好。你是说我必须在拍照后改变图像的位图大小(修改代码)吗?还有一件事让我担心,那就是训练tesseract会影响输出吗? - Jennifer
1
拍照后无需更改位图,只需使用原始图像。我不确定有关Tesseract的培训。 - Abhishek V
2个回答

1

Tesseract-ocr在以下条件满足的字符图像上表现最佳:

  • 输入图像至少应具有300 dpi

  • 输入图像应为黑白色

  • 输入图像中应该没有太多噪声(即文本应该与背景清晰可辨)

  • 文本行应该是直线的

  • 图像应该围绕要检测的文本居中

(请参阅tesseract-ocr wiki获取更多详细信息)

对于给定的输入图像,tesseract将尝试预处理和清理图像以满足这些条件,但为了最大化检测准确性,最好自己进行预处理。

根据您提供的输入图像,主要问题是背景噪音过多。为了从图像中去除文本中的背景噪声,我发现使用带有阈值的笔画宽度变换(SWT)算法可以消除噪声并取得良好的结果。libCCV库提供了可配置参数较多的快速实现SWT功能。该算法清理图像的效果取决于多种因素,包括图像大小、笔画宽度的均匀性以及其他算法的输入参数等。此处提供了可配置参数列表。 然后将SWT的输出传递到tesseract中,以获取图像中字符的文本值。
如果传递给tesseract的图像仍然包含一些噪声,则可能会返回一些错误检测,例如标点符号。鉴于您处理的图像可能只包含字母和数字a-z A-Z 0-9,因此您可以简单地对输出应用正则表达式以去除任何最终的假检测。

0
you can use Vision for text detection.

Add dependency in app gradle

compile 'com.google.android.gms:play-services-vision:10.0.0'

添加到Manifest.xml
<meta-data
        android:name="com.google.android.gms.vision.DEPENDENCIES"
        android:value="ocr" />

MainActivity.java

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_GALLERY = 0;
    private static final int REQUEST_CAMERA = 1;

    private static final String TAG = MainActivity.class.getSimpleName();

    private Uri imageUri;
    private TextView detectedTextView;

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

        findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, REQUEST_GALLERY);
            }
        });

        findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String filename = System.currentTimeMillis() + ".jpg";

                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.TITLE, filename);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, REQUEST_CAMERA);
            }
        });

        detectedTextView = (TextView) findViewById(R.id.detected_text);
        detectedTextView.setMovementMethod(new ScrollingMovementMethod());
    }

    private void inspectFromBitmap(Bitmap bitmap) {
        TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
        try {
            if (!textRecognizer.isOperational()) {
                new AlertDialog.
                        Builder(this).
                        setMessage("Text recognizer could not be set up on your device").show();
                return;
            }

            Frame frame = new Frame.Builder().setBitmap(bitmap).build();
            SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
            List<TextBlock> textBlocks = new ArrayList<>();
            for (int i = 0; i < origTextBlocks.size(); i++) {
                TextBlock textBlock = origTextBlocks.valueAt(i);
                textBlocks.add(textBlock);
            }
            Collections.sort(textBlocks, new Comparator<TextBlock>() {
                @Override
                public int compare(TextBlock o1, TextBlock o2) {
                    int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
                    int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
                    if (diffOfTops != 0) {
                        return diffOfTops;
                    }
                    return diffOfLefts;
                }
            });

            StringBuilder detectedText = new StringBuilder();
            for (TextBlock textBlock : textBlocks) {
                if (textBlock != null && textBlock.getValue() != null) {
                    detectedText.append(textBlock.getValue());
                    detectedText.append("\n");
                }
            }

            detectedTextView.setText(detectedText);
        }
        finally {
            textRecognizer.release();
        }
    }

    private void inspect(Uri uri) {
        InputStream is = null;
        Bitmap bitmap = null;
        try {
            is = getContentResolver().openInputStream(uri);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            options.inSampleSize = 2;
            options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
            bitmap = BitmapFactory.decodeStream(is, null, options);
            inspectFromBitmap(bitmap);
        } catch (FileNotFoundException e) {
            Log.w(TAG, "Failed to find the file: " + uri, e);
        } finally {
            if (bitmap != null) {
                bitmap.recycle();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    Log.w(TAG, "Failed to close InputStream", e);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_GALLERY:
                if (resultCode == RESULT_OK) {
                    inspect(data.getData());
                }
                break;
            case REQUEST_CAMERA:
                if (resultCode == RESULT_OK) {
                    if (imageUri != null) {
                        inspect(imageUri);
                    }
                }
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="org.komamitsu.android_ocrsample.MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/choose_from_gallery"
        android:id="@+id/choose_from_gallery"
        tools:context=".MainActivity"
        android:layout_marginTop="23dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/take_a_photo"
        android:id="@+id/take_a_photo"
        tools:context=".MainActivity"
        android:layout_marginTop="11dp"
        android:layout_below="@+id/choose_from_gallery"
        android:layout_centerHorizontal="true" />


    <TextView
        android:text=""
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/detected_text"
        android:layout_alignParentBottom="true"
        android:layout_below="@+id/take_a_photo"
        android:layout_margin="25dp"
        android:layout_centerHorizontal="true"
        android:background="#EEEEEE"
        android:scrollbars="vertical" />

</RelativeLayout>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接