OpenCV身份证离线识别技术实战(二)
OpenCV身份证离线识别技术实战的终章,首先是集成tess-two到Android完成离线OCR,然后再移植从图像预处理的代码移植到Android上, 这两件事情完成便搞定了身份证号码离线识别的功能了。最后思考一点:如果身份证图像不是正放的应该怎么处理呢?
总体思路
tess-two实现离线OCR
引入依赖:
1implementation 'com.rmtheis:tess-two:9.1.0'
MainActivity.java
1import com.googlecode.tesseract.android.TessBaseAPI;
2
3public class MainActivity extends AppCompatActivity {
4
5 private static final String PATH = "/storage/emulated/0/";
6 // 中文识别的训练结果
7 private static final String MODEL_NAME = "chi_sim.traineddata";
8
9 @Override
10 protected void onCreate(Bundle savedInstanceState) {
11 super.onCreate(savedInstanceState);
12 setContentView(R.layout.activity_main);
13 TextView tv = findViewById(R.id.tv);
14
15 new Thread(()-> {
16 copyTrainedDataToSDCard();
17 TessBaseAPI baseAPI = new TessBaseAPI();
18 baseAPI.setDebug(true);
19 // PATH 下应该包含tessdata文件夹,设置语言简体中文
20 baseAPI.init(PATH, "chi_sim");
21 baseAPI.setImage(xxxx);
22 String utf8Text = baseAPI.getUTF8Text();
23 runOnUiThread(()->{
24 Log.i(TAG, "onCreate: utf8Text = " + utf8Text);
25 tv.setText(utf8Text);
26 });
27 }).start();
28 }
29}
其实通过tess-two实现离线OCR的过程,只需要注意以下几点:
1、经过训练的模型需要放在本地,而且处于tessdata文件夹下(只要模型的文件夹是tessdata就行),如下:
1> adb shell
2HWGLK:/ $ cd /storage/emulated/0/tessdata/
3HWGLK:/storage/emulated/0/tessdata $ ls -ahl
4total 21M
5drwxrwx--x 2 root sdcard_rw 3.4K 2021-12-28 00:21 .
6drwxrwx--x 142 root sdcard_rw 20K 2021-12-29 19:53 ..
7-rw-rw---- 1 root sdcard_rw 42M 2021-12-28 20:26 chi_sim.traineddata
8HWGLK:/storage/emulated/0/tessdata $ pwd
9/storage/emulated/0/tessdata
无论是从网络下载,还是从assets文件夹copy到sdcard,只要模型文件所处的文件夹符合上述规则即可。
2、 https://github.com/tesseract-ocr/tessdata ,可以从这里下载到已经训练好的模型文件,如果要做中文文字识别,那么下载chi_sim.traineddata即可,并且在代码中指定要识别的文字是简体中文(chi_sim)。
3、识别过程最好放在子线程执行,不要阻塞UI线程。
集成OpenCV到Android
我这里直接用OpenCV官网编译好的so库,然后集成到项目即可:
1├─assets
2├─cpp
3│ ├─include
4│ │ ├─opencv
5│ │ └─opencv2
6│ └─libs
7│ └─armeabi-v7a
8├─java
9│ └─cn
10│ └─tim
11│ └─idcard
12└─res
13├─drawable
14├─layout
CMakeLists.txt,由于需要创建Bitmap,所以需要引入jnigraphics这个库:
1cmake_minimum_required(VERSION 3.10.2)
2project('tess_two_ocr')
3
4find_library(jnigraphics-lib jnigraphics)
5
6find_library(log-lib log)
7
8include_directories(include)
9
10link_directories(libs/${ANDROID_ABI})
11
12add_library(native-lib SHARED native-lib.cpp)
13
14target_link_libraries(native-lib ${log-lib} opencv_java3 jnigraphics)
build.gradle
1plugins {
2 id 'com.android.application'
3}
4
5android {
6 compileSdkVersion 30
7 buildToolsVersion "30.0.0"
8
9 defaultConfig {
10 applicationId "cn.tim.tess_two_ocr"
11 minSdkVersion 21
12 targetSdkVersion 30
13 versionCode 1
14 versionName "1.0"
15
16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
17 externalNativeBuild {
18 cmake {
19 cppFlags "-std=c++11"
20 }
21 }
22
23 ndk {
24 // 设置支持的架构平台
25 abiFilters "armeabi-v7a"
26 }
27 }
28
29 buildTypes {
30 release {
31 minifyEnabled false
32 }
33 }
34 externalNativeBuild {
35 cmake {
36 path "src/main/cpp/CMakeLists.txt"
37 version "3.10.2"
38 }
39 }
40 compileOptions {
41 sourceCompatibility JavaVersion.VERSION_1_8
42 targetCompatibility JavaVersion.VERSION_1_8
43 }
44 ndkVersion '21.1.6352462'
45
46 sourceSets {
47 main {
48 // 配置一下库的位置
49 jniLibs.srcDirs = ['src/main/cpp/libs']
50 }
51 }
52}
53
54dependencies {
55 implementation 'androidx.appcompat:appcompat:1.1.0'
56 implementation 'com.google.android.material:material:1.1.0'
57 implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
58 testImplementation 'junit:junit:4.+'
59 androidTestImplementation 'androidx.test.ext:junit:1.1.1'
60 androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
61 // tess-two的依赖
62 implementation 'com.rmtheis:tess-two:9.1.0'
63}
native-lib.cpp
1#include <jni.h>
2#include <android/bitmap.h>
3#include <android/native_window.h>
4#include <android/native_window_jni.h>
5#include <opencv2/opencv.hpp>
6#include <android/log.h>
7
8
9#define LOG_TAG "native"
10
11#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
12
13#define DEFAULT_CARD_WIDTH 640
14#define DEFAULT_CARD_HEIGHT 400
15#define FIX_IDCARD_SIZE Size(DEFAULT_CARD_WIDTH, DEFAULT_CARD_HEIGHT)
16
17extern "C" JNIEXPORT jstring JNICALL
18Java_cn_tim_idcard_MainActivity_stringFromJNI(JNIEnv* env, jobject /* this */) {
19 std::string hello = "Hello from C++";
20 return env->NewStringUTF(hello.c_str());
21}
22
23extern "C" {
24using namespace cv;
25using namespace std;
26
27extern JNIEXPORT void JNICALL Java_org_opencv_android_Utils_nBitmapToMat2
28(JNIEnv *env, jclass, jobject bitmap, jlong m_addr, jboolean needUnPremultiplyAlpha);
29
30extern JNIEXPORT void JNICALL Java_org_opencv_android_Utils_nMatToBitmap
31(JNIEnv *env, jclass, jlong m_addr, jobject bitmap);
32
33jobject createBitmap(JNIEnv *env, Mat srcData, jobject config) {
34 // Image Details
35 int imgWidth = srcData.cols;
36 int imgHeight = srcData.rows;
37
38 LOGI("imgWidth=%d, imgHeight=%d\n", imgWidth, imgHeight);
39 jclass bmpCls = env->FindClass("android/graphics/Bitmap");
40 jmethodID createBitmapMid = env->GetStaticMethodID(bmpCls, "createBitmap", "(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;");
41 jobject jBmpObj = env->CallStaticObjectMethod(bmpCls, createBitmapMid, imgWidth, imgHeight, config);
42 Java_org_opencv_android_Utils_nMatToBitmap(env, nullptr, (jlong) &srcData, jBmpObj);
43 return jBmpObj;
44}
45
46
47JNIEXPORT jobject JNICALL
48Java_cn_tim_idcard_MainActivity_getIdNumber(JNIEnv *env, jclass type, jobject src, jobject config) {
49 Mat src_img;
50 Mat dst_img;
51 // bitmap转换为Mat型格式数据
52 Java_org_opencv_android_Utils_nBitmapToMat2(env, type, src, (jlong) &src_img, 0);
53
54 Mat dst;
55 // 无损压缩 640*400
56 resize(src_img, src_img,FIX_IDCARD_SIZE);
57 // 灰度化
58 cvtColor(src_img, dst, COLOR_BGR2GRAY);
59 // 二值化
60 threshold(dst, dst, 100, 255, CV_THRESH_BINARY);
61 // 膨胀处理
62 Mat erodeElement = getStructuringElement(MORPH_RECT, Size(20, 10));
63 erode(dst, dst, erodeElement);
64 // 轮廓检测
65 vector< vector<Point> > contours;
66 vector<Rect> rects;
67
68 findContours(dst, contours, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
69
70 // 轮廓检测
71 for (auto & contour : contours) {
72 Rect rect = boundingRect(contour);
73 if (rect.width > rect.height * 9) {
74 rects.push_back(rect);
75 rectangle(dst, rect, Scalar(0,255,255));
76 dst_img = src_img(rect);
77 }
78 }
79
80 if (rects.size() == 1) {
81 Rect rect = rects.at(0);
82 dst_img = src_img(rect);
83 }else {
84 int lowPoint = 0;
85 Rect finalRect;
86 for (const auto& rect : rects) {
87 if (rect.tl().y > lowPoint) {
88 lowPoint = rect.tl().y;
89 finalRect = rect;
90 }
91 }
92 rectangle(dst, finalRect, Scalar(255, 255, 0));
93 dst_img = src_img(finalRect);
94 }
95
96 jobject bitmap = createBitmap(env, dst_img, config);
97
98end:
99 src_img.release();
100 dst_img.release();
101 dst.release();
102
103 return bitmap;
104}
105}
完整工程可见, https://github.com/zouchanglin/AndroidProjects/tree/main/tesstwoocr
开始提出的问题?
其实要想解决身份证图像不是正放的最简单的处理方式就是:引导用户正确放置身份证的角度,如下图:
这样在识别不到身份证的情况下提示用户按照框的形式摆放就可以帮我们最大限度的提升处理的效率,根据这样的思路,我将实现一个完整的通过拍照识别 + 提示框辅助的方式来完成身份证识别的Demo。