项目中需要用到身份识别,so网上扫荡了一番,封装了一个比较简单的。
干货如下
需要用到两个三方库 Tesseract-OCR-iOS (识别数字)和 openCV (处理图片)
工程导入以下框架:
TesseractOCR需要用到语言包资源, 文件夹名为tessdata,并拖入工程,如下图
拖入后如下图所示
新建一个OCR类 .m后缀名改为.mm
引入头文件
#import <TesseractOCR/TesseractOCR.h>
#import <opencv2/calib3d/calib3d_c.h>
#import <opencv2/opencv.hpp>
#import <opencv2/imgproc/types_c.h>
#import <opencv2/imgcodecs/ios.h>
首先需要对图片进行处理
- (UIImage *)opencvScanCard:(UIImage *)image {
//将UIImage转换成Mat
cv::Mat resultImage;
UIImageToMat(image, resultImage);
//转为灰度图
cvtColor(resultImage, resultImage, cv::COLOR_BGR2GRAY);
//利用阈值二值化
cv::threshold(resultImage, resultImage, 100, 255, CV_THRESH_BINARY);
//将Mat转换成UIImage
UIImage *numberImage = MatToUIImage(resultImage);
return numberImage;
}
对图片进行读取
-(void)getStringWithOCR:(UIImage *)image Language:(NSString *)language{
G8RecognitionOperation *operation = [[G8RecognitionOperation alloc] initWithLanguage:language];//@"eng" 为英文 可查看语言包资源获得设置不同语言的字符串
/* 识别模式
** G8OCREngineModeTesseractOnly 最快
** G8OCREngineModeCubeOnly 更好但是慢
** G8OCREngineModeTesseractCubeCombined 最慢最准确
*/
operation.tesseract.engineMode = G8OCREngineModeTesseractOnly;
operation.tesseract.pageSegmentationMode = G8PageSegmentationModeAutoOnly;
operation.delegate = self;
//设置image
operation.tesseract.image = [self opencvScanCard:image];
//读取
__block NSString *resultString;
operation.recognitionCompleteBlock = ^(G8Tesseract *tesseract) {
resultString = tesseract.recognizedText;
[[NSNotificationCenter defaultCenter] postNotificationName:@"OCR" object:nil userInfo:@{@"string":resultString}];
};
[self.operationQueue addOperation:operation];
}
以后我们只需调该类-(void)getStringWithOCR:(UIImage *)image Language:(NSString *)language方法即可完成图片识别文字。
ps:过几天补充获得身份证证号图片部分。
网友评论