Пример текстового API Google Mobile Vision

В настоящее время я пишу код, который должен иметь возможность просматривать изображение текста, а затем извлекать текст из изображения для устройств на базе Android. Я провел небольшое исследование в Интернете и обнаружил, что Google предоставляет собственный API под названием «Mobile Vision» (пакет со множеством элементов, например, распознавание текста, распознавание лиц и т. Д.). Однако в своих демонстрациях они демонстрируют только распознавание живого текста. Мне было интересно, может ли кто-нибудь дать мне пример распознавания текста на неподвижном изображении с помощью Mobile Vision API. Любая помощь приветствуется. Спасибо.


person Andrew    schedule 07.07.2016    source источник


Ответы (1)


Документация Google Play Services Mobile Vision API описывает, как это сделать. Вы можете использовать TextRecognizer класс для обнаружения текста в Рамки. Получив растровое изображение, вы можете преобразовать его в кадр и обработать его. См. Пример ниже.

// imageBitmap is the Bitmap image you're trying to process for text
if(imageBitmap != null) {

    TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();

    if(!textRecognizer.isOperational()) {
        // Note: The first time that an app using a Vision API is installed on a
        // device, GMS will download a native libraries to the device in order to do detection.
        // Usually this completes before the app is run for the first time.  But if that
        // download has not yet completed, then the above call will not detect any text,
        // barcodes, or faces.
        // isOperational() can be used to check if the required native libraries are currently
        // available.  The detectors will automatically become operational once the library
        // downloads complete on device.
        Log.w(LOG_TAG, "Detector dependencies are not yet available.");

        // Check for low storage.  If there is low storage, the native library will not be
        // downloaded, so detection will not become operational.
        IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
        boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;

        if (hasLowStorage) {
            Toast.makeText(this,"Low Storage", Toast.LENGTH_LONG).show();
            Log.w(LOG_TAG, "Low Storage");
        }
    }


    Frame imageFrame = new Frame.Builder()
            .setBitmap(imageBitmap)
            .build();

    SparseArray<TextBlock> textBlocks = textRecognizer.detect(imageFrame);

    for (int i = 0; i < textBlocks.size(); i++) {
        TextBlock textBlock = textBlocks.get(textBlocks.keyAt(i));

        Log.i(LOG_TAG, textBlock.getValue()); 
        // Do something with value
    }
}

Вам также необходимо убедиться, что вы включили зависимость мобильного видения в build.gradle модуля.

dependencies {
    compile 'com.google.android.gms:play-services-vision:9.4.0'
} 

А также включите следующее в манифест Android приложения

<meta-data
    android:name="com.google.android.gms.vision.DEPENDENCIES"
    android:value="ocr" />
person businesscasual    schedule 17.09.2016
comment
Привет, используя приведенный выше код, он не обнаруживает все строки. Мне нужно получить все строки из объекта textBlocks, а также нужно получить все значения из textBlock. Пожалуйста, помогите мне как можно скорее. Спасибо заранее ... - person Naveen; 07.10.2016
comment
Чтобы получить строки из текстового блока, просто выполните: List<? extends Text> textComponents = mText.getComponents(); for(Text currentText : textComponents) { // Do your thing here } - person LomaxOnTheRun; 07.02.2017
comment
@ можем ли мы ограничить чтение английского текста только с помощью Vision API? - person Android Developer World; 02.09.2017
comment
@AndroidDeveloperWorld Нет, он распознает 18+ разных языков. Посмотрите, какие языки поддерживаются здесь: developers.google.com/vision/text-overview - person w3bshark; 09.10.2017
comment
@ w3bshark В моем сценарии текст телугу не следует читать на карточке Aadhar. Он должен читать только по-английски. - person Android Developer World; 11.10.2017
comment
можем ли мы отдельно загрузить зависимость от мобильного зрения? - person Chamin Thilakarathne; 24.10.2019