赞
踩
iOS开发-CIDetector识别图片中人脸功能
CIDetector是CoreImage框架中提供的一个识别的类,可以对人脸、形状、条码、文本进行识别。
示例代码
// 创建图形上下文
CIContext * context = [CIContext contextWithOptions:nil];
// 创建自定义参数字典
NSDictionary * param = [NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy];
// 创建识别器对象
CIDetector * faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context:context options:param];
识别人脸,我们首先设置识别的属性option
NSDictionary *options = @{
CIDetectorAccuracy:CIDetectorAccuracyHigh, // 设置检测精确度
CIDetectorEyeBlink:@(YES), // 是否检测眨眼
CIDetectorTracking:@(YES) // 是否追踪人脸
};
之后识别图片中的人脸功能
代码如下
#import "SDFaceDetector.h" @interface SDFaceDetector () /// CIDetector 的配置 @property (nonatomic, strong) NSMutableDictionary *detectorOptions; /// CIDetector @property (nonatomic, strong) CIDetector *faceDetector; @end @implementation SDFaceDetector - (instancetype)init { self = [super init]; if (self) { } return self; } - (void)detectorFace:(CIImage *)ciimage { // 先转换成CGImage // CGImageRef cgImg = [image CGImage]; // 再转换成 CIImage // CIImage *ciImage = [CIImage imageWithCGImage:cgImg]; CIImage *ciImage = ciimage; if (!ciimage) { return; } NSArray<CIFeature *> *features = [self.faceDetector featuresInImage:ciImage options:self.detectorOptions]; NSLog(@"features:%@", features); for (CIFeature *feature in features) { if ([feature isKindOfClass:CIFaceFeature.class]) { CIFaceFeature *faceFeature = (CIFaceFeature *)feature; // 判断是否检测到了嘴巴,是否检测到了左右眼,是否有追踪ID,如果在创建CIDetector 时允许了人脸追踪,则相同的人脸会有相同的trackingID。 if (faceFeature.hasMouthPosition && faceFeature.hasLeftEyePosition && faceFeature.hasRightEyePosition && faceFeature.hasTrackingID) { // faceFeature.bounds 属性保存了人脸的位置信息。 // 处理图像,处理图像的部分,比如裁剪和缩放灰度等,ios原生也能处理,你也可以选择用Opencv处理。 } } } } #pragma mark - Lazy - (NSMutableDictionary *)detectorOptions { if (!_detectorOptions) { NSDictionary *options = @{ CIDetectorAccuracy:CIDetectorAccuracyHigh, // 设置检测精确度 CIDetectorEyeBlink:@(YES), // 是否检测眨眼 CIDetectorTracking:@(YES) // 是否追踪人脸 }; _detectorOptions = [NSMutableDictionary dictionaryWithDictionary:options]; } return _detectorOptions; } - (CIDetector *)faceDetector { if (!_faceDetector) { _faceDetector = [CIDetector detectorOfType:CIDetectorTypeFace context: nil options:self.detectorOptions];; } return _faceDetector; } @end
iOS开发-CIDetector识别图片中人脸功能。
CIDetector是CoreImage框架中提供的一个识别的类,可以对人脸、形状、条码、文本进行识别。
学习记录,每天不停进步。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。