Android ocr--identity card recognition function Realization _android

Source: Internet
Author: User
Tags pack

OCR OpenCV Presumably do process image recognition of the students are not unfamiliar to these two words.

OCR (optical character recognition, optical character recognition) is the process by which electronic devices (such as scanners or digital cameras) check the characters on paper, determine their shape by detecting dark, bright patterns, and then translate shapes into computer text using character recognition methods. This gives me a programming interface, we can identify the text of the picture (some documents we take photos through the phone, directly generated word) identity card recognition, bank card recognition.

What's OpenCV?

OpenCV's full name is: Open Source Computer Vision Library. OpenCV is a BSD-licensed (open source) distributed Cross-platform Computer Vision Library that can be run on Linux, Windows, and Mac OS operating systems. It is lightweight and efficient-consisting of a series of C functions and a small number of C + + classes, and provides interfaces for languages such as Python, Ruby, and Matlab, and implements many common algorithms for image processing and computer vision.

The above is the Baidu Encyclopedia gives the definition of plainly is to give us the class library that programming provides just

Android If you want to use OCR

We can use Google Open source project TESSERACT-OCR

GitHub Download Address: HTTPS://GITHUB.COM/JUSTIN/TESSERACT-OCR

Today I'm not going to say how to compile OCR this thing

The main saying is that the identification of two-dimensional code of this project and TESSERACT-OCR integration into a identification card number process

I'll compile them into class libraries for everyone to use.

The ORC recognition method has been encapsulated into a simple class OCR

Package COM.DYNAMSOFT.TESSOCR; 
Import Android.content.Context; 
Import Android.content.res.AssetManager; 
Import Android.graphics.Bitmap; 
 
Import android.os.Environment; 
 
Import Com.googlecode.tesseract.android.TessBaseAPI; 
 
Import Java.io.File; 
 /** * Created by cyl on 2016/3/26. * Email:670654904@qq.com * This class is called the interface of OCR * This is the identification process is time-consuming operation please put the thread operation/public class OCR {private Tessbaseapi 
  mtess; 
  Private Boolean flag; 
  private context; 
 
  Private Assetmanager Assetmanager; 
    Public OCR () {//TODO auto-generated constructor stub mtess = new Tessbaseapi (); 
    String datapath = environment.getexternalstoragedirectory () + "/tesseract/"; 
    String language = "eng"; 
    Please put your language pack here under the SD tessseract under the tessdata file dir = new file (datapath + "tessdata/"); 
    if (!dir.exists ()) dir.mkdirs (); 
  Flag = Mtess.init (datapath, language); 
/** * Identify the text on the bitmap * @param bitmap need to recognize the picture * @return * *  public string Getocrresult (Bitmap Bitmap) {string result = "Dismiss langues"; 
      if (flag) {mtess.setimage (bitmap); 
    result = Mtess.getutf8text (); 
  return result; 
  public void OnDestroy () {if (mtess!= null) mtess.end (); 
 } 
}

The method is simple:

To create an object, call the Getocrresult method, and note that the identification process is time-consuming and is put into a thread to operate. Avoid ANR problems

Then we need to integrate the recognition into the two-dimensional code scan.

The following is a more detailed description of the two-dimensional Code scanning project

Http://www.jb51.net/article/53487.htm

Here are some of the main classes in the Zxing library and the role of these classes:

    • Captureactivity. This is the starting activity, which is the scanner.
    • Captureactivityhandler decoding processing class, is responsible for calling another thread to decode.
    • Decodethread the decoded thread.
    • Com.google.zxing.client.android.camera bag, Camera control pack.
    • Viewfinderview's Custom view is the box in the middle of the shot we saw.

I can simply think about the image recognition, we need to get the picture to recognize, when the recognition is successful should return the data and feedback to the user we have completed the identification.

First of all, how do we get the image that bitmap from the main function of the class can be seen.

I should go to captureactivityhandler decoding processing to find, regardless of the identification of two-dimensional code or pictures, id ah. Ultimately, it's all about identifying bitmap.

So here we can find the image captured by the camera;

Decodehandler

 * * Copyright (C) zxing authors * * Licensed under the Apache License, Version 2.0 (the "License"); 
 * You could not use this file, except in compliance with the License. * You may obtain a copy of the License in * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by  Applicable or agreed to in writing, software * Distributed under the License be distributed on ' as is ' basis, * 
 Without warranties or CONDITIONS of any KIND, either express or implied. 
 * The License for the specific language governing permissions and * limitations under the License. 
 
* * Package com.sj.app.decoding; 
Import Android.graphics.Bitmap; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.os.Looper; 
Import Android.os.Message; 
 
Import Android.util.Log; 
Import Com.dynamsoft.tessocr.OCR; 
Import Com.google.zxing.BinaryBitmap; 
Import Com.google.zxing.DecodeHintType; 
Import Com.google.zxing.MultiFormatReader; Import COM.GOOGLE.ZXIng. 
Readerexception; 
Import Com.google.zxing.Result; 
Import Com.google.zxing.common.HybridBinarizer; 
Import Com.sj.app.camera.CameraManager; 
Import Com.sj.app.camera.PlanarYUVLuminanceSource; 
Import Com.sj.app.utils.IdMatch; 
Import Com.sj.erweima.MipcaActivityCapture; 
 
Import COM.SJ.ERWEIMA.R; 
Import java.util.Hashtable; 
 
Import java.util.List; 
 
  Final class Decodehandler extends Handler {private static final String TAG = DecodeHandler.class.getSimpleName (); 
  Private final mipcaactivitycapture activity; 
 
  Private final Multiformatreader Multiformatreader; Decodehandler (mipcaactivitycapture activity, Hashtable<decodehinttype, object> hints) {multiFormatRe 
    Ader = new Multiformatreader (); 
    Multiformatreader.sethints (hints); 
  This.activity = activity; 
        @Override public void handlemessage (message message) {switch (message.what) {case R.id.decode: 
        LOG.D (TAG, "Got decode message"); Decode (byTe[]) message.obj, MESSAGE.ARG1, MESSAGE.ARG2); 
      Break 
        Case R.id.quit:looper.mylooper (). Quit (); 
    Break }/** * Decode the data within the viewfinder rectangle, and time how long it * took. 
   For efficiency, reuse the same reader objects from one decode to * the next. 
   * * @param data * The YUV preview frame. 
   * @param the width of the preview frame. 
   * @param Height * The height of the preview frame. 
    * * private void decode (byte[] data, int width, int height) {Long start = System.currenttimemillis (); 
 
    Result rawresult = null; 
    Modify here byte[] Rotateddata = new Byte[data.length];  for (int y = 0; y < height; y++) {for (int x = 0; x < width; x +) rotateddata[x * height + height- 
    Y-1] = data[x + y * Width]; int tmp = width; 
    Here we are are swapping, that's the difference to #11 width = height; Height = tmp; 
    Planaryuvluminancesource Source = Cameramanager.get (). Buildluminancesource (rotateddata, width, height); 
    Binarybitmap bitmap = new Binarybitmap (new Hybridbinarizer (source)); 
      The Bitmap image captured in the try {//camera = Source.rendercroppedgreyscalebitmap (); 
      DOORC (source); 
    Rawresult = Multiformatreader.decodewithstate (bitmap); 
    The catch (Readerexception re) {//Continue} finally {Multiformatreader.reset (); 
      } if (Rawresult!= null) {Long end = System.currenttimemillis (); 
      LOG.D (TAG, "Found barcode" ("+ (End-start) +" ms): \ n "+ rawresult.tostring ()); 
      Message message = Message.obtain (Activity.gethandler (), r.id.decode_succeeded, Rawresult); 
      Bundle Bundle = new Bundle (); 
      Bundle.putparcelable (Decodethread.barcode_bitmap, Source.rendercroppedgreyscalebitmap ()); 
      Message.setdata (bundle); LOG.D (TAG, "sending Decode succeededMessage ... "); 
    Message.sendtotarget (); 
      else {Message message = Message.obtain (Activity.gethandler (), r.id.decode_failed); 
    Message.sendtotarget (); } private Handler Handler = new Handler () {public void Handlemessage (msg) {Cardid Cardid = (C 
      Ardid) Msg.obj; if (Cardid!= null) {Message message = Message.obtain (Activity.gethandler (), r.id.decode_succeeded, C 
        Ardid.id); 
        Bundle Bundle = new Bundle (); 
        Bundle.putparcelable (Decodethread.barcode_bitmap, Cardid.bitmap); 
        Message.setdata (bundle); 
        LOG.D (TAG, "Sending decode succeeded message ..."); 
      Message.sendtotarget (); 
  } 
    }; 
  }; private void Doorc (final planaryuvluminancesource source) {New Thread (new Runnable () {@Override publi 
        c void Run () {Bitmap Bitmap = Source.rendercroppedgreyscalebitmap (); String id = new OCR (). Getocrresult (BitmAP); 
          if (ID!= null) {list<string> List = Idmatch.machid (ID); 
            if (list!= null && list.size () >0) {String Cardid = list.get (0); 
              if (Cardid!= null) {Message msg = Message.obtain (); 
              Cardid cardId2 = new Cardid (Cardid, bitmap); 
              Msg.obj = CARDID2; 
            Handler.sendmessage (msg); 
  }}}). Start (); 
    public class cardid{private String ID; 
    Private Bitmap Bitmap; 
      Public Cardid (String ID, Bitmap Bitmap) {super (); 
      This.id = ID; 
    This.bitmap = bitmap; 
    Public String GetId () {return id; 
    public void SetId (String id) {this.id = ID; 
    Public Bitmap Getbitmap () {return Bitmap; 
    public void SetBitmap (Bitmap Bitmap) {this.bitmap = Bitmap; 
 } 
 
  } 
 
}

When the parse succeeds, the result is returned to the UI thread via handler, and we can respond to the adjustment for the scan box.

Cameramanager This class controls the size of the scan box.

Public Rect Getframingrect () {point 
  screenresolution = Configmanager.getscreenresolution (); 
  if (Framingrect = = null) { 
   if (camera = null) {return 
    null; 
   } 
   int width = screenresolution.x * 7/8; 
   if (Width < min_frame_width) { 
    width = min_frame_width; 
   } else if (Width > max_frame_width) { 
//    W Idth = max_frame_width; 
   } 
   int height = screenresolution.y * 3/4; 
   if (height < min_frame_height) { 
    height = min_frame_height 
   } else if (height > max_frame_height) { 
    h eight = max_frame_height; 
   } 
   int leftoffset = (screenresolution.x-width)/2; 
   int topoffset = (screenresolution.y-height)/2; 
   Framingrect = new Rect (LeftOffset, Topoffset, LeftOffset + width, topoffset + height); 
   LOG.D (TAG, "calculated framing Rect:" + framingrect); 
  } 
  return framingrect; 
 } 

Changing this method can change the size of the scan box.

You need to be prompted if your phone is Android more than 6.0 please check the SD card root directory exists Tesseract/tessdata directory and the following file if not present the application did not get the storage permissions.

Original link: http://blog.csdn.net/tiandiyinghun/article/details/50985961

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.