iOS Vision框架(人脸识别、文本检测等)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HDFQQ188816190/article/details/85234137

ios 11+macOS 10.13+ 新出了Vision框架,Face Detection and Recognition(人脸检测识别)、Machine Learning Image Analysis(机器学习图片分析)、Barcode Detection(条形码检测)、Text Detection(文本检测)、目标跟踪等功能,它是基于Core ML的。可以说是人工智能的一部分。

tips:此框架和coreImage框架 有某种类似。可互相联系学习。

一、API架构

Vision框架一共包括以下类:

VNRequestHandler :继承自NSObject的VNImageRequestHandler 和 VNSequenceRequestHandler。

VNRequest :图像分析请求的抽象超类

VNObservation : 图像分析结果的抽象超类

VNFaceLandmarks :面部信息类

VNError : 错误信息类

VNUtils :工具类

VNTypes

两个协议:VNRequestRevisionProviding 和 VNFaceObservationAccepting

二、使用

1、流程:给各种功能的 Request 提供给一个 RequestHandler,RequestHandler持有需要识别的图片信息,并将处理结果分发给每个 Request 的 completion Block 中。可以从 results 属性中得到 Observation 信息数组。

2、示例:

  UIImage *img = [UIImage imageNamed:@"shsh.jpg"];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(20, 200, img.size.width, img.size.height);
    imageView.image = img;
    [self.view addSubview:imageView];
    UIView *resultView = [[UIView alloc] initWithFrame:imageView.frame];
    [self.view addSubview:resultView];
    
    // CIImage
    CIImage *convertImage = [CIImage imageWithCGImage:img.CGImage];
    // 创建处理requestHandler
    VNImageRequestHandler *handler = [[VNImageRequestHandler alloc] initWithCIImage:convertImage options:@{}];
    // 创建BaseRequest
    VNImageBasedRequest *request = [[VNDetectFaceRectanglesRequest alloc]initWithCompletionHandler:^(VNRequest * _Nonnull request, NSError * _Nullable error) {
        NSArray *observations = request.results;

        // 得到Observation
        VNFaceObservation *faceObservation = observations.firstObject;
        
        CGRect rect = faceObservation.boundingBox; //返回识别区域的比例值
        
        CGFloat X = rect.origin.x * img.size.width;
        CGFloat W = rect.size.width * img.size.width;
        CGFloat H = rect.size.height * img.size.height;
        CGFloat Y = img.size.height * (1 - rect.origin.y) - H; // Y比例值是距离底部的
        UIView *faceView = [[UIView alloc] initWithFrame:CGRectMake(X, Y, W, H)];
        faceView.layer.borderColor = [UIColor redColor].CGColor;
        faceView.layer.borderWidth = 1;
        [resultView addSubview:faceView];
    }];
    // 发送识别请求
    [handler performRequests:@[request] error:nil];

参考:

https://www.jianshu.com/p/3790d67db004

http://www.cocoachina.com/ios/20170801/20061.html

-- NORMAL --

-- NORMAL --

-- NORMAL --

-- NORMAL --

猜你喜欢

转载自blog.csdn.net/HDFQQ188816190/article/details/85234137