iOS CoreImage之脸部识别

CoreImage一个好玩的地方就是它可以检测出一张人物图片上左眼、右眼以及嘴的详细位置。请注意这里使用的是“检测”而不是“识别”。CoreImage目前还没有办法识别人脸仅仅是检测出人脸的眼嘴位置。

它的使用也是比较方便快捷的。核心代码如下:

    UIImage *image = [UIImage imageNamed:@"baby.jpg"];
    CIImage *begingImage = [[CIImage alloc] initWithImage:image];
    
    //创建CIDetector对象,options使用NSDictionary设置采用高品质还是低品质,这里使用低品质。
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:[NSDictionary dictionaryWithObject:CIDetectorAccuracyLow forKey:CIDetectorAccuracy]];
    //返回数组中包含图片脸部特征信息
    NSArray *faceFeatures = [detector featuresInImage:begingImage];
    
    for (CIFaceFeature *faceFeature in faceFeatures) {
        //脸部宽度
        CGFloat faceWidth = faceFeature.bounds.size.width;
        //左眼的判断
        if (faceFeature.hasLeftEyePosition) {
            
            UIView *leftEyeView = [[UIView alloc] initWithFrame:CGRectMake(faceFeature.leftEyePosition.x - faceWidth * 0.15, faceFeature.leftEyePosition.y - faceWidth * 0.15, faceWidth * 0.3, faceWidth * 0.3)];
            leftEyeView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.3];
            [self.view addSubview:leftEyeView];
        }
        
        //右眼的判断
        if (faceFeature.hasRightEyePosition) {
            
            UIView *rightEyeView = [[UIView alloc] initWithFrame:CGRectMake(faceFeature.rightEyePosition.x - faceWidth * 0.15, faceFeature.rightEyePosition.y - faceWidth * 0.15, faceWidth * 0.3, faceWidth * 0.3)];
            rightEyeView.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.3];
            [self.view addSubview:rightEyeView];
        }
        
        //嘴的判断
        if (faceFeature.hasMouthPosition) {
            
            UIView *monthView = [[UIView alloc] initWithFrame:CGRectMake(faceFeature.mouthPosition.x - 0.2 * faceWidth, faceFeature.mouthPosition.y - faceWidth * 0.2, faceWidth * 0.4, faceWidth * 0.4)];
            monthView.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.3];
            [self.view addSubview:monthView];
        }
    }
    
    self.imageView.image = image;
    [self.imageView sizeToFit];
    
    //旋转
    self.imageView.transform = CGAffineTransformMakeScale(1, -1);
    self.view.transform = CGAffineTransformMakeScale(1, -1);
需要注意的是:CIImage的坐标系和UIKit的坐标系是不同的。CIImage的坐标系原点在屏幕的左下角,而UIKit的坐标系原点在屏幕的左上角,所以坐标系需要经过变换。

效果图:



另外就是做了一下卡通人物、动物的图片试验,CoreImage的效果很不错,只有在人物的图片上显示了标记。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值