項目中需要用到身份識別航瞭,so網(wǎng)上掃蕩了一番,封裝了一個比較簡單的钞钙。
干貨如下?
需要用到兩個三方庫 Tesseract-OCR-iOS (識別數(shù)字)和 openCV?(處理圖片)
工程導(dǎo)入以下框架:
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>
首先需要對圖片進(jìn)行處理
- (UIImage *)opencvScanCard:(UIImage *)image {
//將UIImage轉(zhuǎn)換成Mat
cv::Mat resultImage;
UIImageToMat(image, resultImage);
//轉(zhuǎn)為灰度圖
cvtColor(resultImage, resultImage, cv::COLOR_BGR2GRAY);
//利用閾值二值化
cv::threshold(resultImage, resultImage, 100, 255, CV_THRESH_BINARY);
//將Mat轉(zhuǎn)換成UIImage
UIImage *numberImage = MatToUIImage(resultImage);
return numberImage;
}
對圖片進(jìn)行讀取
-(void)getStringWithOCR:(UIImage *)image Language:(NSString *)language{
G8RecognitionOperation *operation = [[G8RecognitionOperation alloc] initWithLanguage:language];//@"eng" 為英文? 可查看語言包資源獲得設(shè)置不同語言的字符串
/*? 識別模式
**? G8OCREngineModeTesseractOnly? 最快
**? G8OCREngineModeCubeOnly? ? ? 更好但是慢
**? G8OCREngineModeTesseractCubeCombined? 最慢最準(zhǔn)確
*/
operation.tesseract.engineMode = G8OCREngineModeTesseractOnly;
operation.tesseract.pageSegmentationMode = G8PageSegmentationModeAutoOnly;
operation.delegate = self;
//設(shè)置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];
}
以后我們只需調(diào)該類-(void)getStringWithOCR:(UIImage *)image Language:(NSString *)language方法即可完成圖片識別文字芒炼。
ps:過幾天補(bǔ)充獲得身份證證號圖片部分瘫怜。