“This is my 33rd day of participating in the First Challenge 2022. For details: First Challenge 2022.”

The introduction

Intelligent recognition range:

Business license recognition, bank card recognition, passport recognition, driving license recognition, printed text recognition, image content recognition

Application scenarios:

2. Automatic filling of ID card number: online application of credit card, entry of merchant and real-name authentication

Principle: The self-defined camera collects bank card pictures and invokes SDK/API for OCTR recognition

Related articles:

IOS13 scanning certificate & text recognition; Id card identification (positive and negative); Rectangular edge recognition; Custom camera: add a rectangular frame and cut the ID photo

Kunnan.blog.csdn.net/article/det…

IOS custom camera (with shooting area frame, translucent mask layer, click the screen focus, automatic cutting) : 1, ID card front and back camera (add a rectangular frame and cut ID photo) 2, handheld id camera (including demo source)

— — — — — — — —

Copyright notice: This article is an original article BY CSDN blogger “# public account: iOS Reverse”, in accordance with CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement. The original link: blog.csdn.net/z929118967/…

I Encapsulated OCR interface (charge)

Market.aliyun.com/products/57…

Call address: HTTP (s) : / / ocrcard.market.alicloudapi.com/textread

Request mode: POST

Return type: JSON

The name of the type Whether must describe
side STRING optional Front: front, front: back, license identification This parameter is optional
src STRING Will choose The image is base64 encoded
tid STRING optional Driving License: XSZ, driving License: JSZ, Business License: YYZZ; Bank card: YHK; Recognize all by default: simple; Business License: YYZZB;

1.1 Official iOS version

Tid parameters can be opened to adapt to different application scenarios

NSString *appcode = @" Your own AppCode";
NSString *host = @"https://ocrcard.market.alicloudapi.com";
NSString *path = @"/textread";
NSString *method = @"POST";
NSString *querys = @ "";
NSString *url = [NSString stringWithFormat:@ % @ % @ % @ "",  host,  path , querys];
NSString *bodys = @"side=front&src=%E5%9B%BE%E7%89%87base64%E7%BC%96%E7%A0%81&tid=simple";

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]  cachePolicy:1  timeoutInterval:  5];
request.HTTPMethod  =  method;
[request addValue:  [NSString  stringWithFormat:@"APPCODE %@" ,  appcode]  forHTTPHeaderField:  @"Authorization"];
[request addValue: @"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField: @"Content-Type"];
NSData *data = [bodys dataUsingEncoding: NSUTF8StringEncoding];
[request setHTTPBody: data];
NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request
    completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSLog(@"Response object: %@" , response);
    NSString *bodyString = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];

    // Prints the body in the reply
    NSLog(@"Response body: %@" , bodyString);
    }];

[task resume];

Copy the code

1.2 Self-encapsulated iOS version

Type = @”simple”; Identification head file for the front and back of the ID card

@interface OcrIdentify : NSObject

+ (void)OCRIdentifyType:(NSString *)type Image:(UIImage *)image success:(void(^) (id responseObj))success failure:(void(^) (NSError *error))failure;
/** Handle special cases of business licenses */
+ (BOOL)isover_a_long_period_of_time:(NSString*)str;


Copy the code

The implementation code


/ * * the if ([STR isEqualToString: @ "business term"]) {/ / "business term" : "/ /" for a long time, the if ([responseObj [@ "MSG"] [STR] isEqualToString: @ "long-term"]) {* /
+ (BOOL)isover_a_long_period_of_time:(NSString*)str{
    
    if ([str isEqualToString:Long-term "@"]) {// "business term" : "\/ long term ",
        
        return YES;

    }
    
    
     if([str containsString:Long-term "@"] && !([str containsString:@ "to"])){
        
        return YES;

        
        
        
        
    }
    
    
    
    
    return NO;
}
/** http(s)://ocrphoto.market.alicloudapi.com/ocr/photo */
+ (void)OCRIdentifyType:(NSString *)type Image:(UIImage *)image success:(void(^) (id responseObj))success failure:(void(^) (NSError *error))failure
{
    NSString *appcode = @ "";
    NSString *host = @"http://ocrcard.market.alicloudapi.com";
    NSString *path = @"/textread";
    NSString *method = @"POST";
    NSString *querys = @ "";
    NSString *url = [NSString stringWithFormat:@ % @ % @ % @ "",  host,  path , querys];

    NSData *imgData = UIImageJPEGRepresentation(image, 0.1f);
    NSString *base64 = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    base64 = [self encodeString:base64];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]  cachePolicy:1  timeoutInterval:  5];
    request.HTTPMethod  =  method;
    [request addValue:  [NSString  stringWithFormat:@"APPCODE %@" ,  appcode]  forHTTPHeaderField:  @"Authorization"];
    [request addValue: @"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField: @"Content-Type"];
    NSString *bodys = [NSString stringWithFormat:@"src=%@&tid=%@",base64,type];
    NSData *data = [bodys dataUsingEncoding: NSUTF8StringEncoding];
    [request setHTTPBody: data];
    
    NSURLSession *requestSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [requestSession dataTaskWithRequest:request
                                                   completionHandler:^(NSData * _Nullable body , NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                       
                                                       if(! error) {NSError * _Nonnull error;
                                                           NSString *jsonStr = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
                                                           NSData *JSONData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
                                                           NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:&error];
                                                           if (error)
                                                           {
                                                               if(failure)
                                                               {
                                                                   NSLog(@ "% @",error.userInfo); failure(error); }}if (success)
                                                           {
                                                               if(responseJSON ! =nil) {
                                                                   NSLog(@"body:%@ url:%@"The [[NSString alloc] initWithData: [NSJSONSerialization dataWithJSONObject:responseJSON options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding],url);
                                                               }

                                                               if ([responseJSON[@"status"] intValue] == 200) {
                                                                   success(responseJSON);
                                                               } else {
// [SVProgressHUD showInfoWithStatus:responseJSON[@"msg"]];
                                                                   [SVProgressHUD showInfoWithStatus:@" Misidentified!"]; }}}}]; [task resume]; } + (NSString*)encodeString:(NSString*)unencodedString{
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@! "" * '(); : @ & = + $, /? % # []",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

Copy the code

1.3 usage



        
        
        type = @"simple";

        [OcrIdentify OCRIdentifyType:type Image:photo success:^(id  _Nonnull responseObj) {
            
            
            
            NSArray *array = [responseObj[@"msg"] componentsSeparatedByString:@"\n"];
            for (int i = 0; i < array.count; i++) {
                if (weakSelf.photoSelectTag == 0) {
                    if ([array[i] containsString:@" Citizenship number"]) {
                        if ([array[i]length] > 6) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                NSString *idCard = [array[i] substringFromIndex:6];
                                weakSelf.frCardTextF.text = [idCard stringByReplacingOccurrencesOfString:@" " withString:@ ""]; }); }}else if ([array[i] containsString:@ "name"]) {
                        if ([array[i]length] > 2) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                NSString *tmpcardNameTextFT = [array[i] substringFromIndex:2];
                                
                                tmpcardNameTextFT = [tmpcardNameTextFT stringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceCharacterSet]]; weakSelf.frNameTextF.text = tmpcardNameTextFT; }); }}}else if (weakSelf.photoSelectTag == 1) {
                    // Start date on the reverse side of id card
                    NSString *date = @ "";
                    for (int i = 0; i < array.count; i++) {
                        if ([array[i] containsString:@" Expiry Date"]) {
                            date = [array[i] substringFromIndex:4];
                            date = [date stringByReplacingOccurrencesOfString:@" " withString:@ ""]; }}NSArray *dateArr = [date componentsSeparatedByString:@ "-"];
                    if (dateArr.count == 2) {
                        for (int i = 0; i < dateArr.count; i++) {
                            if (i == 0) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    self->frsta = [dateArr[0] stringByReplacingOccurrencesOfString:@ "." withString:@ "-"];
                                });
                            } else if (i == 1) {
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    if ([dateArr[1]containsString:Long-term "@"]) {
                                        self->frend = @ "";
                                        [weakSelf.frDateBtn setTitle:[NSString stringWithFormat:@ "% @ ~ for a long time".self->frsta] forState:UIControlStateNormal];
                                        
                                    } else {
                                        self->frend = [dateArr[1] stringByReplacingOccurrencesOfString:@ "." withString:@ "-"];
                                        [weakSelf.frDateBtn setTitle:[NSString stringWithFormat:@ % @ ~ % @ "".self->frsta,self->frend] forState:UIControlStateNormal]; }}); }}}else {
                        [SVProgressHUD showErrorWithStatus:@" ID error!"];
                    }
                }
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD showErrorWithStatus:@" ID error!"];
        }];
Copy the code

1.4 Common Problems

  1. AppCode: Console – Cloud Marketplace – Purchased service

  1. If there is any problem, submit the work order directly:

Ticket.console.aliyun.com/?spm=5176.1…

License plate call address:

[http(s)://ocrcp.market.alicloudapi.com/rest/160601/ocr/ocr_vehicle_plate.json

Request type: POST Return type: JSON Request parameter (Body) : {"image": "Base64 encoding of image binary data or image URL"# base64 encoded string}Copy the code

II Free SDK please download from CSDN:

2.1 Scanning bank card identification information Demo source code

From CSDN download Demo source: download.csdn.net/download/u0…

  1. Function: Scan bank card identification information (bank name, bank card number) and capture bank card image

  2. Application scenario: Rapid filling of bank card number, such as merchant entry and real-name authentication

  3. Principle:

3.1. Customize the camera and use third-party libraries SDK LibexBankCardios. a and libbexbankcard.a for identification (unlimited identification times, free)

3.2. Add a custom scanning interface (with a hollow window in the middle and a scanning line moving back and forth)

  1. Principle: kunnan.blog.csdn.net/article/det…

  2. If you can’t download the Demo, please pay attention to the public account: [iOS reverse], to get the picture description inserted here

2.2 Identification card information

From CSDN download Demo source: https://download.csdn.net/download/u011018979/19265912

  1. Function: it can automatically and quickly read the information on the second generation ID card (name, gender, nationality, address, ID number) and intercept the id card image
  2. Application scenario: COLLECTION of ID card number: credit card online application, merchant entry, real-name authentication
  3. Principle:

3.1. Customize the camera and use the third-party library SDK LibexidCardios for identification

3.2. Add a custom scanning interface (with a hollow window in the middle and a scanning line moving back and forth)

3.3, face small box detection: whether the face area is in the face small box, if in, that the user does put the ID head in this box, then this frame ID image size is just right and complete, then capture the frame, you get a complete ID screenshot.

  1. Principle: kunnan.blog.csdn.net/article/det…

2.3 Customized camera for bank card identification

Principle:Self-defined camera collects bank card pictures and invokes SDK/API for OCTR recognition

IOS custom camera (with shooting area border, translucent mask layer, click screen focus, auto cropping) :

  1. Id card front and back camera (add a rectangular frame and cut out the ID card photo)

  2. Hand-held certificate camera

— — — — — — — —

Copyright notice: This article is an original article BY CSDN blogger “# public account: iOS Reverse”, in accordance with CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement. The original link: blog.csdn.net/z929118967/…

2.4 General character recognition

From CSDN download Demo source: https://download.csdn.net/download/u011018979/19262418

1. Application scenarios: DOCUMENT scanning and text recognition

2, principle: using iOS13 VNDocumentCameraViewController certificate scanning and VNRecognizeTextRequest character recognition function is implemented

Principle 3, article: kunnan.blog.csdn.net/article/det…

see also

🍅 Contact author: iOS Reverse (public number: iosrev)


🍅 Author profile: CSDN blog expert certification 🏆 international Top 50, Huawei Cloud enjoy expert certification 🏆, iOS reverse public number master


🍅 Resume template, technical assistance. Pay attention to me, all for you.