Android Open Source - nsa-away Simple O C R Activity






From Project

Back to project page nsa-away.

License

The source code is released under:

GNU General Public License

If you think the Android project nsa-away listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * Copyright 2014 individual contributors as indicated by the @author 
 * tags//from   w w w  . j  av  a2s.c o m
 * 
 * This is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this software.  If not, see <http://www.gnu.org/licenses/>. 
 */
package org.sector67.nsaaway;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.googlecode.tesseract.android.TessBaseAPI;

/**
 * Based on code from https://github.com/GautamGupta/Simple-Android-OCR
 * 
 * @author scott.hasse@gmail.com
 *
 */
public class SimpleOCRActivity extends Activity {
  public static final String PACKAGE_NAME = "org.sector67.nsaaway";
  public static final String DATA_PATH = Environment
      .getExternalStorageDirectory().toString() + "/NSAAway/";
  
  // You should have the trained data file in assets folder
  // You can get them at:
  // http://code.google.com/p/tesseract-ocr/downloads/list
  public static final String lang = "eng";

  private static final String TAG = SimpleOCRActivity.class.toString();

  protected Button _button;
  // protected ImageView _image;
  protected EditText _field;
  protected String _path;
  protected boolean _taken;

  protected static final String PHOTO_TAKEN = "photo_taken";

  @Override
  public void onCreate(Bundle savedInstanceState) {

    String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };

    for (String path : paths) {
      File dir = new File(path);
      if (!dir.exists()) {
        if (!dir.mkdirs()) {
          Log.e(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
          //TODO: show alert
          return;
        } else {
          Log.v(TAG, "Created directory " + path + " on sdcard");
        }
      }

    }
    
    // lang.traineddata file with the app (in assets folder)
    // You can get them at:
    // http://code.google.com/p/tesseract-ocr/downloads/list
    // This area needs work and optimization
    if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
      try {

        AssetManager assetManager = getAssets();
        InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
        //GZIPInputStream gin = new GZIPInputStream(in);
        OutputStream out = new FileOutputStream(DATA_PATH
            + "tessdata/" + lang + ".traineddata");

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        //while ((lenf = gin.read(buff)) > 0) {
        while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }
        in.close();
        //gin.close();
        out.close();
        
        Log.v(TAG, "Copied " + lang + " traineddata");
      } catch (IOException e) {
        Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
      }
    }

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_simple_ocr);

    // _image = (ImageView) findViewById(R.id.image);
    _field = (EditText) findViewById(R.id.field);
    _button = (Button) findViewById(R.id.button);
    _button.setOnClickListener(new ButtonClickHandler());

    _path = DATA_PATH + "/ocr.jpg";
  }

  public class ButtonClickHandler implements View.OnClickListener {
    public void onClick(View view) {
      Log.v(TAG, "Starting Camera app");
      startCameraActivity();
    }
  }

  // Simple android photo capture:
  // http://labs.makemachine.net/2010/03/simple-android-photo-capture/

  protected void startCameraActivity() {
    File file = new File(_path);
    Uri outputFileUri = Uri.fromFile(file);

    final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

    startActivityForResult(intent, 0);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.i(TAG, "resultCode: " + resultCode);

    if (resultCode == -1) {
      onPhotoTaken();
    } else {
      Log.v(TAG, "User cancelled");
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(SimpleOCRActivity.PHOTO_TAKEN, _taken);
  }

  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    Log.i(TAG, "onRestoreInstanceState()");
    if (savedInstanceState.getBoolean(SimpleOCRActivity.PHOTO_TAKEN)) {
      onPhotoTaken();
    }
  }

  protected void onPhotoTaken() {
    _taken = true;

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 4;

    Bitmap bitmap = BitmapFactory.decodeFile(_path, options);

    try {
      ExifInterface exif = new ExifInterface(_path);
      int exifOrientation = exif.getAttributeInt(
          ExifInterface.TAG_ORIENTATION,
          ExifInterface.ORIENTATION_NORMAL);

      Log.v(TAG, "Orient: " + exifOrientation);

      int rotate = 0;

      switch (exifOrientation) {
      case ExifInterface.ORIENTATION_ROTATE_90:
        rotate = 90;
        break;
      case ExifInterface.ORIENTATION_ROTATE_180:
        rotate = 180;
        break;
      case ExifInterface.ORIENTATION_ROTATE_270:
        rotate = 270;
        break;
      }

      Log.v(TAG, "Rotation: " + rotate);

      if (rotate != 0) {

        // Getting width & height of the given image.
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        // Setting pre rotate
        Matrix mtx = new Matrix();
        mtx.preRotate(rotate);

        // Rotating Bitmap
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
      }

      // Convert to ARGB_8888, required by tess
      bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

    } catch (IOException e) {
      Log.e(TAG, "Couldn't correct orientation: " + e.toString());
    }

    // _image.setImageBitmap( bitmap );
    
    Log.v(TAG, "Before baseApi");

    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.setDebug(true);
    baseApi.init(DATA_PATH, lang);
        baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, "ABCDEFabcdef0123456789");

    baseApi.setImage(bitmap);
    
    String recognizedText = baseApi.getUTF8Text();
    
    baseApi.end();

    // You now have the text in recognizedText var, you can do anything with it.
    // We will display a stripped out trimmed alpha-numeric version of it (if lang is eng)
    // so that garbage doesn't make it to the display.

    Log.v(TAG, "OCRED TEXT: " + recognizedText);

    if ( lang.equalsIgnoreCase("eng") ) {
      recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
    }
    
    recognizedText = recognizedText.trim();

    if ( recognizedText.length() != 0 ) {
      _field.setText(_field.getText().toString().length() == 0 ? recognizedText : _field.getText() + " " + recognizedText);
      _field.setSelection(_field.getText().toString().length());
    }
    
  }

}




Java Source Code List

org.sector67.nsaaway.CreateAKeyActivity.java
org.sector67.nsaaway.DisplayCiphertextActivity.java
org.sector67.nsaaway.DisplayPlaintextActivity.java
org.sector67.nsaaway.EnterCiphertextActivity.java
org.sector67.nsaaway.EnterPlaintextActivity.java
org.sector67.nsaaway.KeyChooserActivity.java
org.sector67.nsaaway.KeyChooserDialogFragment.java
org.sector67.nsaaway.KeyManagerActivity.java
org.sector67.nsaaway.MainActivity.java
org.sector67.nsaaway.SettingsActivity.java
org.sector67.nsaaway.SettingsFragment.java
org.sector67.nsaaway.SimpleOCRActivity.java
org.sector67.nsaaway.android.AlertUtils.java
org.sector67.nsaaway.file.AbstractFileUtils.java
org.sector67.nsaaway.file.DirectoryChooserActivity.java
org.sector67.nsaaway.file.FileUtilsFactory.java
org.sector67.nsaaway.file.FileUtils.java
org.sector67.nsaaway.file.KitKatFileUtils.java
org.sector67.nsaaway.file.LegacyFileUtils.java
org.sector67.nsaaway.key.KeyUtils.java
org.sector67.nsaaway.ocr.complex.BeepManager.java
org.sector67.nsaaway.ocr.complex.CaptureActivityHandler.java
org.sector67.nsaaway.ocr.complex.CaptureActivity.java
org.sector67.nsaaway.ocr.complex.DecodeHandler.java
org.sector67.nsaaway.ocr.complex.DecodeThread.java
org.sector67.nsaaway.ocr.complex.FinishListener.java
org.sector67.nsaaway.ocr.complex.HelpActivity.java
org.sector67.nsaaway.ocr.complex.LuminanceSource.java
org.sector67.nsaaway.ocr.complex.OcrCharacterHelper.java
org.sector67.nsaaway.ocr.complex.OcrInitAsyncTask.java
org.sector67.nsaaway.ocr.complex.OcrRecognizeAsyncTask.java
org.sector67.nsaaway.ocr.complex.OcrResultFailure.java
org.sector67.nsaaway.ocr.complex.OcrResultText.java
org.sector67.nsaaway.ocr.complex.OcrResult.java
org.sector67.nsaaway.ocr.complex.PlanarYUVLuminanceSource.java
org.sector67.nsaaway.ocr.complex.PreferencesActivity.java
org.sector67.nsaaway.ocr.complex.ViewfinderView.java
org.sector67.nsaaway.ocr.complex.camera.AutoFocusManager.java
org.sector67.nsaaway.ocr.complex.camera.CameraConfigurationManager.java
org.sector67.nsaaway.ocr.complex.camera.CameraManager.java
org.sector67.nsaaway.ocr.complex.camera.PreviewCallback.java
org.sector67.nsaaway.ocr.complex.camera.ShutterButton.java
org.sector67.nsaaway.ocr.complex.language.LanguageCodeHelper.java