編輯:關於 Android 程式設計
做過圖像識別的同學,對 OCR 和 OpenCV 這兩個詞想必都不陌生。
OCR(Optical Character Recognition,光學字符識別)是指電子設備(如掃描儀、數碼相機)檢測紙面字符的明暗模式、判斷其形狀,再通過識別算法把形狀轉譯為計算機文本的過程。它為我們的編程提供了接口,讓我們能夠直接從圖片中提取文字,進而衍生出身份證識別、銀行卡識別等應用。
那 OpenCV 又是什麼?
OpenCV 全稱 Open Source Computer Vision Library,是一個基於 BSD 許可開源發行的跨平台計算機視覺庫,可運行於 Linux、Windows、Mac OS 等系統。它由一系列 C 函數和少量 C++ 類構成,並提供了 Python、Ruby、MATLAB 等多語言接口,封裝了大量圖像處理與計算機視覺的通用算法。通俗地說,它就是一套供我們編程調用的視覺類庫。
在 Android 上使用 OCR,我們可以借助 Google 開源的 Tesseract-OCR 項目:
GitHub 下載地址:https://github.com/justin/tesseract-ocr
本篇不糾結於如何編譯 OCR,重點在於把「二維碼掃描項目」與 Tesseract-OCR 整合,做出一個能識別身份證號碼的完整流程,後續再將它們編譯成類庫供大家使用。
OCR 識別方法已封裝為一個簡單的 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 * 這個類 就是調用 ocr 的接口 * 這個是識別過程是耗時的 操作 請放到線程 操作 */ public class OCR { private TessBaseAPI mTess; private boolean flag; private Context context; private AssetManager assetManager; public OCR() { // TODO Auto-generated constructor stub mTess = new TessBaseAPI(); String datapath = Environment.getExternalStorageDirectory() + "/tesseract/"; String language = "eng"; //請將你的語言包放到這裡 sd 的 tessseract 下的tessdata 下 File dir = new File(datapath + "tessdata/"); if (!dir.exists()) dir.mkdirs(); flag = mTess.init(datapath, language); } /** * 識別出來bitmap 上的文字 * @param bitmap 需要識別的圖片 * @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(); } }
用法很簡單:創建對象,調用 getOCRResult 傳入圖片即可。要特別注意的是,識別過程是耗時操作,務必放到子線程中執行,避免引發 ANR。
接著,我們要把識別能力集成進二維碼掃描項目中。關於二維碼掃描項目的詳細介紹可參考:https://www.jb51.net/article/53487.htm
這裡先梳理一下 ZXing 庫中幾個關鍵類及其職責:
思路其實很清晰:無論是識別二維碼、圖片還是身份證,最終都是對 Bitmap 進行處理,所以我們需要先在解碼流程裡拿到相機捕捉到的圖像。相關邏輯可以在 CaptureActivityHandler 的解碼處理中找到。下面看 DecodeHandler 的實現:
/* * Copyright (C) 2010 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See 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) { multiFormatReader = 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 width * 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 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)); try { //相機中捕捉到的 Bitmap image = source.renderCroppedGreyscaleBitmap(); doorc(source); rawResult = multiFormatReader.decodeWithState(bitmap); } 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 succeeded message..."); message.sendToTarget(); } else { Message message = Message.obtain(activity.getHandler(), R.id.decode_failed); message.sendToTarget(); } } private Handler handler = new Handler(){ public void handleMessage(Message msg) { CardId cardId = (CardId) msg.obj; if(cardId != null){ Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, cardId.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 public 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; } } }
當解析成功後,結果會通過 Handler 回传到 UI 線程,掃描框也可以相應地做調整。
CameraManager 類控制掃描框大小,核心的 getFramingRect 方法如下:
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) { // width = MAX_FRAME_WIDTH; } int height = screenResolution.y * 3 / 4; if (height < MIN_FRAME_HEIGHT) { height = MIN_FRAME_HEIGHT; } else if (height > MAX_FRAME_HEIGHT) { height = 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; }
修改這個方法,就能改變掃描框的大小。
最後要提醒的是:如果你的手機是 Android 6.0 以上,請先確認 SD 卡根目錄下是否存在 tesseract/tessdata 目錄及相關語言包文件;若不存在,說明應用尚未獲得存儲權限,需要先動態申請。
原文鏈接:https://blog.csdn.net/tiandiyinghun/article/details/50985961
以上就是本篇 OCR 身份證識別的完整實現思路,希望對大家的學習有所幫助。
徹底搞懂 Android 的 layout_weight:剩餘空間到底是怎麼分的
寫 Demo 時碰到 layout_weight,網上關於它的討論很多,但多數說法流於口訣——「值越小權重越大」這類結論背誦起來容易,遇到實際問題就完全用不上。我自己把資
Android 仿餓了麼加入購物車的伸縮旋轉按鈕
這個效果以純自定義 View 實作,不依賴多層 ViewGroup 組合。它可以在數量為 0 時顯示提示文字,點擊後展開加號與減號,並在增減數量時播放旋轉、位移與透明
ActivityManagerService 啟動過程剖析:SystemServer 裡的六個關鍵步驟
之前談 View 繪製原理時曾經提到,setContentView() 之後會走到 preDraw 相關的流程,那裡就牽涉到 ActivityManagerService
Android For JNI(四):C 數組、指針、堆棧內存與 malloc
在 JNI 開發中,C 語言基礎是無法繞開的一環。本文將圍繞 C 語言中的數組、指針、堆內存、棧內存以及 malloc 函數展開,並通過一個簡單的學生學號管理示例,幫助大