Exemple #1
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    window.requestFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.capture);
    baseApi = new TessBaseAPI();

    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    Bitmap mp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

    mp = mp.copy(Bitmap.Config.ARGB_8888, false);
    baseApi.setImage(mp);

    String value = baseApi.getUTF8Text();
    //		Log.d("tag", " the value is ===> " + value);
    baseApi.clear();
    baseApi.end();

    mainSurface = (SurfaceView) findViewById(R.id.mainSurface);
    textView = (TextView) findViewById(R.id.text);
    msurfaceHolder = mainSurface.getHolder();
  }
  @SmallTest
  public void testInit() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Attempt to shut down the API.
    baseApi.end();
  }
  // Scan the photo for text using the tess-two API
  public static String scanPhoto(Bitmap bitmap) {

    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.setDebug(true);
    baseApi.init(DATA_PATH, lang);
    // set the black list
    baseApi.setVariable("tessedit_char_blacklist", "':;,.?/\\}][{!@#$%^&*()-_=+~");
    baseApi.setVariable("save_blob_choices", "T");

    baseApi.setImage(bitmap);

    String recognizedText = baseApi.getUTF8Text();

    // Iterate over the results and print confidence values for debugging purposes
    final ResultIterator iterator = baseApi.getResultIterator();
    String lastUTF8Text;
    float lastConfidence;
    iterator.begin();
    do {
      lastUTF8Text = iterator.getUTF8Text(PageIteratorLevel.RIL_WORD);
      lastConfidence = iterator.confidence(PageIteratorLevel.RIL_WORD);
      if (lastConfidence > 50) {
        Log.d(TAG, String.format("%s => %.2f", lastUTF8Text, lastConfidence));
      }

    } while (iterator.next(PageIteratorLevel.RIL_WORD));

    baseApi.end();

    Log.d(TAG, recognizedText);

    return recognizedText;
  }
  @SmallTest
  public void testEnd() {
    final String inputText = "hello";
    final Bitmap bmp = getTextImage(inputText, 640, 480);

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
    baseApi.setImage(bmp);

    // Ensure that getUTF8Text() fails after end() is called.
    baseApi.end();
    try {
      baseApi.getUTF8Text();
      fail("IllegalStateException not thrown");
    } catch (IllegalStateException e) {
      // Continue
    } finally {
      bmp.recycle();
    }

    // Ensure that reinitializing the API is successful.
    boolean success = baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    assertTrue("API failed to initialize after end()", success);

    // Ensure setImage() does not throw an exception.
    final Bitmap bmp2 = getTextImage(inputText, 640, 480);
    baseApi.setImage(bmp2);

    // Attempt to shut down the API.
    baseApi.end();
    bmp2.recycle();
  }
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == 10) {
     if (resultCode == RESULT_OK) {
       byte[] datas = data.getExtras().getByteArray("data");
       baseApi.setImage(BitmapFactory.decodeByteArray(datas, 0, datas.length));
       tv_capture.setText(baseApi.getUTF8Text());
     }
   }
 }
  @SmallTest
  public void testInit_ocrEngineMode() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    boolean result = baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE, TessBaseAPI.OEM_TESSERACT_ONLY);

    assertTrue("Init was unsuccessful.", result);

    // Attempt to shut down the API.
    baseApi.end();
  }
  @SmallTest
  public void testGetInitLanguagesAsString() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Check the last-used language code.
    String lang = baseApi.getInitLanguagesAsString();
    assertEquals("Got incorrect init languages value.", lang, DEFAULT_LANGUAGE);

    // Attempt to shut down the API.
    baseApi.end();
  }
  @SuppressWarnings("unused")
  private OcrResult getOcrResult() {
    OcrResult ocrResult;
    String textResult;
    long start = System.currentTimeMillis();

    try {
      baseApi.setImage(ReadFile.readBitmap(bitmap));
      textResult = baseApi.getUTF8Text();
      timeRequired = System.currentTimeMillis() - start;

      // Check for failure to recognize text
      if (textResult == null || textResult.equals("")) {
        return null;
      }
      ocrResult = new OcrResult();
      ocrResult.setWordConfidences(baseApi.wordConfidences());
      ocrResult.setMeanConfidence(baseApi.meanConfidence());
      if (ViewfinderView.DRAW_REGION_BOXES) {
        ocrResult.setRegionBoundingBoxes(baseApi.getRegions().getBoxRects());
      }
      if (ViewfinderView.DRAW_TEXTLINE_BOXES) {
        ocrResult.setTextlineBoundingBoxes(baseApi.getTextlines().getBoxRects());
      }
      if (ViewfinderView.DRAW_STRIP_BOXES) {
        ocrResult.setStripBoundingBoxes(baseApi.getStrips().getBoxRects());
      }

      // Always get the word bounding boxes--we want it for annotating the bitmap after the user
      // presses the shutter button, in addition to maybe wanting to draw boxes/words during the
      // continuous mode recognition.
      ocrResult.setWordBoundingBoxes(baseApi.getWords().getBoxRects());

      //      if (ViewfinderView.DRAW_CHARACTER_BOXES || ViewfinderView.DRAW_CHARACTER_TEXT) {
      //        ocrResult.setCharacterBoundingBoxes(baseApi.getCharacters().getBoxRects());
      //      }
    } catch (RuntimeException e) {
      Log.e(
          "OcrRecognizeAsyncTask",
          "Caught RuntimeException in request to Tesseract. Setting state to CONTINUOUS_STOPPED.");
      e.printStackTrace();
      try {
        baseApi.clear();
        activity.stopHandler();
      } catch (NullPointerException e1) {
        // Continue
      }
      return null;
    }
    timeRequired = System.currentTimeMillis() - start;
    ocrResult.setBitmap(bitmap);
    ocrResult.setText(textResult);
    ocrResult.setRecognitionTimeRequired(timeRequired);
    return ocrResult;
  }
  @SmallTest
  public void testSetImage_bitmap() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Set the image to a Bitmap.
    final Bitmap bmp = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);
    baseApi.setImage(bmp);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
  @SmallTest
  public void testWordConfidences() {
    final String inputText = "one two three";
    final Bitmap bmp = getTextImage(inputText, 640, 480);

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_BLOCK);

    baseApi.setImage(bmp);
    String text = baseApi.getUTF8Text();

    assertNotNull("Recognized text is null.", text);

    // Ensure that a mean confidence value is returned.
    int conf = baseApi.meanConfidence();
    boolean validConf = conf > 0 && conf <= 100;
    assertTrue("Mean confidence value is incorrect.", validConf);

    // Ensure that word confidence values are returned.
    int numWords = text.split("\\s+").length;
    int[] wordConf = baseApi.wordConfidences();
    assertEquals("Found the wrong number of word confidence values.", numWords, wordConf.length);
    for (int i = 0; i < wordConf.length; i++) {
      boolean valid = 0 <= wordConf[i] && wordConf[i] <= 100;
      assertTrue("Found an invalid word confidence value.", valid);
    }

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
  @SmallTest
  public void testSetImage_pix() throws IOException {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Set the image to a Pix.
    Pix pix = new Pix(640, 480, 32);
    baseApi.setImage(pix);

    // Attempt to shut down the API.
    baseApi.end();
    pix.recycle();
  }
Exemple #12
0
  /**
   * 识别图片并取值
   *
   * @param bitmap
   * @return
   */
  public String decodeBitmapValue(Bitmap bitmap) {
    if (bitmap == null) {
      return null;
    }
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, false);
    baseApi.setImage(bitmap); // 识别图片

    String value = baseApi.getUTF8Text();
    //		Log.d("tag", " the value is ===> " + value);
    baseApi.clear();
    baseApi.end();
    return value;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    copyAssets();
    baseApi = new TessBaseAPI();
    baseApi.init(DATA_PATH, "eng");

    extractedText = (TextView) findViewById(R.id.extractedText);
    croppedImage = (ImageView) findViewById(R.id.croppedImage);
    camera = (Button) findViewById(R.id.camera);

    camera.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            try {
              Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
              startActivityForResult(intent, PIC_CAPTURE);
            } catch (ActivityNotFoundException e) {
              String noCamera = "Your phone doesnot support image capture";
              Toast toast = Toast.makeText(getApplicationContext(), noCamera, Toast.LENGTH_LONG);
              toast.show();
            }
          }
        });
  }
 protected String tessProcess(Bitmap bMap) {
   TessBaseAPI tessapi = new TessBaseAPI();
   // tessapi.init("/storage/sdcard0/", "eng");
   tessapi.init(Environment.getExternalStorageDirectory().toString(), "eng");
   // ImageView image = (ImageView)findViewById(R.id.test_image);
   // Bitmap bMap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() +
   // "/tessdata/sample_input.bmp");
   // image.setImageBitmap(bMap);
   tessapi.setImage(bMap);
   String txt = tessapi.getUTF8Text();
   tessapi.end();
   // Log.i(TAG, "OCR output:\n" + txt);
   // TextView my_out_1 = (TextView)findViewById(R.id.my_out);
   // my_out_1.setText("Hello:" + txt);
   return txt;
 }
Exemple #15
0
  public String getTextContent() {
    Log.d("whathaeljf", "The second image path is " + imagePath);
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

    /*
            Matrix matrix = new Matrix();
            matrix.postRotate(180);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    */
    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.setDebug(true);
    baseApi.init(DATA_PATH, lang);

    baseApi.setImage(bitmap);
    String recognizedText = baseApi.getUTF8Text();
    return recognizedText;
  }
  @SmallTest
  public void testSetRectangle() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_CHAR);

    final int width = 640;
    final int height = 480;
    final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    final Paint paint = new Paint();
    final Canvas canvas = new Canvas(bmp);

    canvas.drawColor(Color.WHITE);

    paint.setColor(Color.BLACK);
    paint.setStyle(Style.FILL);
    paint.setAntiAlias(true);
    paint.setTextAlign(Align.CENTER);
    paint.setTextSize(32.0f);

    // Draw separate text on the left and right halves of the image.
    final String leftInput = "A";
    final String rightInput = "B";
    canvas.drawText(leftInput, width / 4, height / 2, paint);
    canvas.drawText(rightInput, width * 3 / 4, height / 2, paint);

    baseApi.setVariable(TessBaseAPI.VAR_CHAR_WHITELIST, leftInput + rightInput);
    baseApi.setImage(bmp);

    // Ensure the result is correct for a rectangle on the left half of the image.
    Rect left = new Rect(0, 0, width / 2, height);
    baseApi.setRectangle(left);
    String leftResult = baseApi.getUTF8Text();
    assertEquals("Found incorrect text.", leftInput, leftResult);

    // Ensure the result is correct for a rectangle on the right half of the image.
    Rect right = new Rect(width / 2, 0, width, height);
    baseApi.setRectangle(right);
    String rightResult = baseApi.getUTF8Text();
    assertEquals("Found incorrect text.", rightInput, rightResult);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
  @SmallTest
  public void testSetImage_file() throws IOException {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Create an image file.
    File file = File.createTempFile("testSetImage", ".bmp");
    FileOutputStream fileStream = new FileOutputStream(file);

    Bitmap bmp = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);
    bmp.compress(CompressFormat.JPEG, 85, fileStream);

    // Set the image to a File.
    baseApi.setImage(file);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
  @SmallTest
  public void testGetThresholdedImage() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Set the image to a Bitmap.
    final Bitmap bmp = Bitmap.createBitmap(640, 480, Bitmap.Config.ARGB_8888);
    baseApi.setImage(bmp);

    // Check the size of the thresholded image.
    Pix pixd = baseApi.getThresholdedImage();
    assertNotNull("Thresholded image is null.", pixd);
    assertEquals(bmp.getWidth(), pixd.getWidth());
    assertEquals(bmp.getHeight(), pixd.getHeight());

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
    pixd.recycle();
  }
  @SmallTest
  public void testProgressValues() {
    final String inputText = "hello";
    final Bitmap bmp = getTextImage(inputText, 640, 480);
    final Rect imageBounds = new Rect(0, 0, bmp.getWidth(), bmp.getHeight());

    class Notifier implements ProgressNotifier {
      public boolean receivedProgress = false;

      @Override
      public void onProgressValues(ProgressValues progressValues) {
        receivedProgress = true;
        testProgressValues(progressValues, imageBounds);
      }
    }

    final Notifier notifier = new Notifier();

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI(notifier);
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
    baseApi.setImage(bmp);

    // Ensure that we receive a progress callback.
    baseApi.getHOCRText(0);
    assertTrue(notifier.receivedProgress);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
  private void textExtraction(Bitmap croppedPic) {
    int width, height;
    height = croppedPic.getHeight();
    width = croppedPic.getWidth();

    Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(bmpGrayscale);
    Paint paint = new Paint();
    ColorMatrix cm = new ColorMatrix();
    cm.setSaturation(0);
    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);
    c.drawBitmap(croppedPic, 0, 0, paint);

    baseApi.setImage(bmpGrayscale);
    baseApi.setImage(baseApi.getThresholdedImage());
    String recognizedText = baseApi.getUTF8Text();
    recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9\\s]+", "");
    extractedText.setText(recognizedText);

    croppedImage.setImageBitmap(bmpGrayscale);
  }
Exemple #21
0
  public void ocr_main() {
    Log.v(TAG, "entering tess");

    // Getting uri of image/cropped image
    try {
      myimage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), image_uri);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // Log.v(TAG, "bitmap " + myimage.getByteCount());
    //        Bitmap argb = myimage;
    //        argb = argb.copy(Bitmap.Config.ARGB_8888, true);
    //        Log.v(TAG, "bitmap after argb:" + argb.getByteCount());
    //
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inSampleSize = 2;
    myimage = BitmapFactory.decodeFile(filepath, opt);
    // Log.v(TAG, "bitmap after comp:" + myimage.getByteCount());

    // TessBase starts
    TessBaseAPI baseApi = new TessBaseAPI();

    baseApi.setDebug(true);
    baseApi.init(DATA_PATH, lang);
    Log.v(TAG, "Before baseApi");
    baseApi.setImage(myimage);
    Log.v(TAG, "Before baseApi2");
    String recognizedText = baseApi.getUTF8Text();
    Log.v(TAG, "Before baseApi3");
    baseApi.end();

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

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

    // recognizedText is the final OCRed text
    recognizedText = recognizedText.trim();

    //		String ocrtext = "And...BAM! OCRed: " + recognizedText;
    //		Toast toast = Toast.makeText(this.getApplicationContext(), ocrtext,
    //				Toast.LENGTH_LONG);
    //		toast.show();

    // deleting temporary crop file created
    File file =
        new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "temp.bmp");
    boolean deleted = file.delete();
    Log.i(TAG, "File deleted: " + deleted);

    Intent intent = new Intent(this, ResultActivity.class);
    intent.putExtra("ocrText", recognizedText);
    startActivity(intent);
  }
  /**
   * Perform an OCR decode for realtime recognition mode.
   *
   * @param data Image data
   * @param width Image width
   * @param height Image height
   */
  private void ocrContinuousDecode(byte[] data, int width, int height) {
    PlanarYUVLuminanceSource source =
        activity.getCameraManager().buildLuminanceSource(data, width, height);
    if (source == null) {
      sendContinuousOcrFailMessage();
      return;
    }
    bitmap = source.renderCroppedGreyscaleBitmap();

    OcrResult ocrResult = getOcrResult();
    Handler handler = activity.getHandler();
    if (handler == null) {
      return;
    }

    if (ocrResult == null) {
      try {
        sendContinuousOcrFailMessage();
      } catch (NullPointerException e) {
        activity.stopHandler();
      } finally {
        bitmap.recycle();
        baseApi.clear();
      }
      return;
    }

    try {
      Message message = Message.obtain(handler, R.id.ocr_continuous_decode_succeeded, ocrResult);
      message.sendToTarget();
    } catch (NullPointerException e) {
      activity.stopHandler();
    } finally {
      baseApi.clear();
    }
  }
Exemple #23
0
  public void doOCR(Bitmap bitmap) {
    Bitmap BiBitmap = Binary.preProcess(bitmap);
    mImage2.setImageBitmap(BiBitmap);
    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(datapath, language);
    // 必须加此行,tess-two要求BMP必须为此配置
    bitmap = BiBitmap.copy(Bitmap.Config.ARGB_8888, true);
    baseApi.setImage(bitmap);
    String result = baseApi.getUTF8Text();
    baseApi.clear();
    baseApi.end();

    mResult.setText(result);
  }
  @SmallTest
  public void testChoiceIterator() {
    final String inputText = "hello";
    final Bitmap bmp = TessBaseAPITest.getTextImage(inputText, 640, 480);

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TessBaseAPITest.TESSBASE_PATH, TessBaseAPITest.DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
    baseApi.setVariable(TessBaseAPI.VAR_SAVE_BLOB_CHOICES, TessBaseAPI.VAR_TRUE);

    // Ensure that text is recognized.
    baseApi.setImage(bmp);
    String recognizedText = baseApi.getUTF8Text();
    assertTrue("No recognized text found.", recognizedText != null && !recognizedText.equals(""));

    // Iterate through the results.
    ResultIterator iterator = baseApi.getResultIterator();
    List<Pair<String, Double>> choicesAndConfidences;
    iterator.begin();
    do {
      choicesAndConfidences = iterator.getChoicesAndConfidence(PageIteratorLevel.RIL_SYMBOL);
      assertNotNull("Invalid result.", choicesAndConfidences);

      for (Pair<String, Double> choiceAndConfidence : choicesAndConfidences) {
        String choice = choiceAndConfidence.first;
        Double conf = choiceAndConfidence.second;
        assertTrue("No choice value found.", choice != null && !choice.equals(""));
        assertTrue("Found an incorrect confidence value.", conf >= 0 && conf <= 100);
      }
    } while (iterator.next(PageIteratorLevel.RIL_SYMBOL));
    iterator.delete();

    assertNotNull("No ChoiceIterator values found.", choicesAndConfidences);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
Exemple #25
0
 public void initialize() {
   btn_camera = (Button) findViewById(R.id.btn_camera);
   btn_camera.setOnClickListener(
       new View.OnClickListener() {
         @Override
         public void onClick(View v) {
           startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), 10);
         }
       });
   tv_capture = (TextView) findViewById(R.id.tv_capture);
   // Init TessTwoApi
   File dir = new File(getFilesDir().getPath() + "/tessdata");
   if (!dir.exists()) {
     dir.mkdir();
   }
   CreateFileFromAssets.getInstance().initialize(MainActivity.this).CreateFileFromPath("tessdata");
   File f = new File(getFilesDir().getPath() + "/tessdata/eng.traineddata");
   Log.d("TAg,", getFilesDir().getPath() + "/tessdata/eng.traineddata");
   baseApi = new TessBaseAPI();
   baseApi.init(getFilesDir().getPath(), "eng");
 }
  @SmallTest
  public void testClear() {
    final String inputText = "hello";
    final Bitmap bmp = getTextImage(inputText, 640, 480);

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
    baseApi.setImage(bmp);

    // Ensure that the getUTF8Text() operation fails after clear() is called.
    baseApi.clear();
    String text = baseApi.getUTF8Text();

    assertNull("Received non-null result after clear().", text);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
  @SmallTest
  public void testSetVariable() {
    final String inputText = "hello";
    final Bitmap bmp = getTextImage(inputText, 640, 480);

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);

    // Ensure that setting the blacklist variable works.
    final String blacklistedCharacter = inputText.substring(1, 2);
    baseApi.setVariable(TessBaseAPI.VAR_CHAR_BLACKLIST, blacklistedCharacter);
    baseApi.setImage(bmp);
    final String outputText = baseApi.getUTF8Text();
    assertFalse("Found a blacklisted character.", outputText.contains(blacklistedCharacter));

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }
Exemple #28
0
  /*Begin citation: http://gaut.am/making-an-ocr-android-app-using-tesseract/
  gets the image from the external storage directory and uses the tess-two library
  to process the image and return the recognized text
   */
  public String getOCRText() {
    Bitmap bitmap = BitmapFactory.decodeFile(DIR + "ocrImage.jpg");

    TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.setDebug(true);
    baseApi.init(DIR, "eng");
    baseApi.setImage(bitmap);

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

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

    Log.d(DolchListActivity.TAG, recognizedText);

    return recognizedText.trim();
  }
  @SmallTest
  public void testSetPageSegMode() {
    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);

    // Check the default page segmentation mode.
    assertEquals(
        "Found unexpected default page segmentation mode.",
        baseApi.getPageSegMode(),
        DEFAULT_PAGE_SEG_MODE);

    // Ensure that the page segmentation mode can be changed.
    final int newPageSegMode = TessBaseAPI.PageSegMode.PSM_SINGLE_CHAR;
    baseApi.setPageSegMode(newPageSegMode);
    assertEquals(
        "Found unexpected page segmentation mode.", baseApi.getPageSegMode(), newPageSegMode);

    // Attempt to shut down the API.
    baseApi.end();
  }
  private void testGetHOCRText(String language, int ocrEngineMode) {
    final String inputText = "hello";
    final Bitmap bmp = getTextImage(inputText, 640, 480);

    // Attempt to initialize the API.
    final TessBaseAPI baseApi = new TessBaseAPI();
    baseApi.init(TESSBASE_PATH, DEFAULT_LANGUAGE);
    baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_SINGLE_LINE);
    baseApi.setImage(bmp);

    // Ensure that getHOCRText() produces a result.
    final String hOcr = baseApi.getHOCRText(0);
    assertNotNull("HOCR result not found.", hOcr);
    assertTrue(hOcr.length() > 0);

    final String outputText = Html.fromHtml(hOcr).toString().trim();
    assertEquals(inputText, outputText);

    // Attempt to shut down the API.
    baseApi.end();
    bmp.recycle();
  }