旷视人脸识别

1、首先申请账号下载SDK
https://faceid.com/faceopen/login
2、从后台申请appkey

#define api_key @"B8n0Ey1jtG_rdcXPt1ixkh_hi8gUtIhH"
#define api_secret @"41Hj4-hl3swt66gpXor9IUwus6OBaDA8"

3、请求https://api.megvii.com/faceid/v3/sdk/get_biz_token获取
这个函数的值initMGFaceIDLiveDetectManagerWithBizToken:
4、请求https://api.megvii.com/faceid/v3/sdk/verify"获取识别结果

附上代码

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    UIButton* detectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:detectButton];
    [detectButton setBounds:CGRectMake(0, 0, 100, 44)];
    [detectButton setCenter:self.view.center];
    [detectButton setTitle:@"Detect" forState:UIControlStateNormal];
    [detectButton setTitleColor:[UIColor whiteColor]
                       forState:UIControlStateNormal];
    [detectButton setTitleColor:[UIColor lightGrayColor]
                       forState:UIControlStateHighlighted];
    [detectButton setBackgroundColor:[UIColor blueColor]];
    [detectButton addTarget:self
                     action:@selector(startFaceIDLiveDetect:)
           forControlEvents:UIControlEventTouchUpInside];
}
//接口用于配置人脸比对的身份核实功能,支持有源比对(调用者提供姓名、身份证号、和待核实人脸图)和无源比对(直接比对待核实人脸图和参照人脸图)。客户通过服务器将本次活体相关的配置传到FaceID服务器,在验证无误后,返回本次业务的biz_token,用FaceID MegLiveStill SDK的初始化。
-(void)requestData{
    NSString* sign = [self getSignStr];
    NSString *url = @"https://api.megvii.com/faceid/v3/sdk/get_biz_token";
//    liveness_type  meglive:动作活体   still:静默活体
//  comparison_type 0:表示无源比对 1:表示有源比对

    //有源
//    UIImage *originImage = [UIImage imageNamed:@"mine"];
//    UIImage *scale = [self scaleImage:originImage toKb:100];
//    NSData *imagedata = UIImagePNGRepresentation(scale);
    
//        NSString *encodedImageStr = [imagedata base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSDictionary *parameters = @{@"sign":sign,@"sign_version":@"hmac_sha1",@"liveness_type":@"meglive",@"comparison_type":@"1",@"idcard_name":@"胡淑贞",@"idcard_number":@"362229199301111029"};//,@"image_ref1":imagedata
    //无源
//    NSDictionary *parameters = @{@"sign":sign,@"sign_version":@"hmac_sha1",@"liveness_type":@"meglive",@"comparison_type":@"0",@"uuid":@"胡淑贞",@"image_ref1":imagedata};

    [[BaseHttpRequest sharedInstance]sendPOSTHttpRequest:url parameters:parameters success:^(id dicData) {
        NSLog(@"数据%@",dicData);
        NSDictionary *dicDatas = [self dictionaryWithJsonString:dicData];
        self.biz_token = [dicDatas objectForKey:@"biz_token"];
        self.time_used = [dicDatas objectForKey:@"time_used"];
        self.request_id = [dicDatas objectForKey:@"request_id"];
    } error:^(NSString *errorInfo) {
        NSLog(@"%@",errorInfo);
    }];
    
}
//接口用于将FaceID MegLiveStill SDK 所获得的数据进行上传,并获取活体验证、人脸比对、攻击防范等结果信息
-(void)deliverBackData{
    NSString* sign = [self getSignStr];
    NSString *url = @"https://api.megvii.com/faceid/v3/sdk/verify";
    NSString *encodedImageStr = [self.meglive_data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSDictionary *parameters = @{@"sign":sign,@"sign_version":@"hmac_sha1",@"biz_token":self.biz_token,@"meglive_data":encodedImageStr};
    
    [[BaseHttpRequest sharedInstance]sendPOSTHttpRequest:url parameters:parameters success:^(id dicData) {
        NSLog(@"上传接口返回数据%@",dicData);

        
    } error:^(NSString *errorInfo) {
        NSLog(@"上传接口失败%@",errorInfo);
    }];
    
}
-(void)shangchuanData{
    NSString* sign = [self getSignStr];
    NSDictionary * body = @{@"sign":sign,@"sign_version":@"hmac_sha1",@"biz_token":self.biz_token};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", @"text/javascript",@"image/jpeg",@"image/png",@"application/octet-stream", nil];
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
    NSString *url = @"https://api.megvii.com/faceid/v3/sdk/verify";
    [manager POST:url parameters:body constructingBodyWithBlock:^(id  _Nonnull formData) {
        //把image  转为data , POST上传只能传data
//        NSData *data = UIImagePNGRepresentation(image);
        //上传的参数(上传图片,以文件流的格式)
        [formData appendPartWithFileData:self.meglive_data
                                    name:@"file"
                                fileName:@"mine.png"
                                mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"上传成功%@",dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败%@",error);
        
    }];
    

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Detect
- (void)startFaceIDLiveDetect:(UIButton *)sender {
    
    sender.userInteractionEnabled = NO;
    MGFaceIDLiveDetectError* error;
    MGFaceIDLiveDetectManager* liveDetectManager = [[MGFaceIDLiveDetectManager alloc] initMGFaceIDLiveDetectManagerWithBizToken:self.biz_token
                                                                                                                      extraData:@{} error:&error];
    if (error || !liveDetectManager) {
        sender.userInteractionEnabled = YES;
        return;
    }
    [liveDetectManager startMGFaceIDLiveDetectWithCurrentController:self
                                                           callback:^(MGFaceIDLiveDetectError *error, NSData *deltaData, NSString *bizTokenStr, NSDictionary *extraOutDataDict) {
                                                               self.meglive_data = deltaData;
                                                               NSLog(@"错误信息%@=======数据%@============TTT%@==========字典======%@",error,self.meglive_data,bizTokenStr,extraOutDataDict);
                                                               [self deliverBackData];
//                                                               [self shangchuanData];
                                                               sender.userInteractionEnabled = YES;
                                                           }];
}
- (NSString*)getSignStr {
    int validdurtion = 10000;
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];   //获取当前时间 0秒后的时间
    NSTimeInterval currenttime = [date timeIntervalSince1970];
    long int expiretime = currenttime + validdurtion;
    long random = labs(arc4random() % 100000000000);
    NSString* str = [NSString stringWithFormat:@"a=%@&b=%ld&c=%f&d=%ld" ,api_key,expiretime,currenttime,random];
    const char *cKey  = [api_secret cStringUsingEncoding:NSUTF8StringEncoding];
    const char *cData = [str cStringUsingEncoding:NSUTF8StringEncoding];
    
    char cHMAC[CC_SHA1_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
    NSData *HMAC = [[NSData alloc]initWithBytes:cHMAC length:sizeof(cHMAC)];
    NSData* sign_raw_data = [str dataUsingEncoding:NSUTF8StringEncoding ];
    NSMutableData* data = [[NSMutableData alloc] initWithData:HMAC];
    [data appendData:sign_raw_data];
    NSString* sign = [data base64EncodedStringWithOptions:0];
    return sign;
}
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }else {
        return dic;
    }
}
-(UIImage *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    if (!image) {
        return image;
    }
    if (kb<1) {
        return image;
    }
    kb*=1024;
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"当前大小:%fkb",(float)[imageData length]/1024.0f);
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
}

你可能感兴趣的:(旷视人脸识别)