苹果原生OCR识别

2023-08-06  本文已影响0人  song91425
- (void)documentCameraViewController:(UIImage *)image
{
    if (@available(iOS 13.0, *)) {
        VNRecognizeTextRequest *request = [[VNRecognizeTextRequest alloc] initWithCompletionHandler:^(VNRequest * _Nonnull request, NSError * _Nullable error) {
            if (error) {
                NSLog(@"%@", error);
                return;
            }
            NSLog(@"开始识别");
            int i =1;
            for (VNRecognizedTextObservation *observation in request.results) {
                NSString *text = [observation topCandidates:1].firstObject.string;
                NSLog(@"识别片段%d -> 识别结果:%@",i, text);
                i++;
            }
            NSLog(@"识别结束");
            self.needRecoNewSampleBuffer = YES;
            self.needNewSampleBuffer = YES;
        }];
        request.recognitionLevel = VNRequestTextRecognitionLevelAccurate; // 可以选择 accurate 或 fast 两种模式
//        request.recognitionLanguages =  @[@"zh"];
        NSArray<NSString *> *customWords = @[@"姓名", @"性别", @"出生", @"住址",@"公民身份证号码"];
        [request setCustomWords:customWords];
        // 设置识别区域和识别语言
        request.regionOfInterest = CGRectMake(0, 0, 1, 1); // 全图识别
        request.recognitionLanguages = @[@"zh-Hans"]; // 指定识别语言为中文
        VNImageRequestHandler *handler = [[VNImageRequestHandler alloc] initWithCGImage:image.CGImage options:@{}];
        [handler performRequests:@[request] error:nil];
        
    } else {
        // Fallback on earlier versions
    }
}
上一篇下一篇

猜你喜欢

热点阅读