iOS的CoreImage已经内建了人脸检测的接口,检测准确率一般,尤其是侧脸,基本上就检测不到。不过跟其他同类产品比较,也还算是不相上下吧。用起来很简单:
CIImage* image = [CIImage imageWithCGImage:aImage.CGImage]; NSDictionary *opts = [NSDictionary dictionaryWithObject:CIDetectorAccuracyHigh forKey:CIDetectorAccuracy]; CIDetector* detector = [CIDetector detectorOfType:CIDetectorTypeFace context:nil options:opts]; //得到面部数据 NSArray* features = [detector featuresInImage:image];
最后的features中就是检测到的全部脸部数据,可以用如下方式计算位置:
for (CIFaceFeature *f in features) { CGRect aRect = f.bounds; NSLog(@"%f, %f, %f, %f", aRect.origin.x, aRect.origin.y, aRect.size.width, aRect.size.height); //眼睛和嘴的位置 if(f.hasLeftEyePosition) NSLog(@"Left eye %g %g\n", f.leftEyePosition.x, f.leftEyePosition.y); if(f.hasRightEyePosition) NSLog(@"Right eye %g %g\n", f.rightEyePosition.x, f.rightEyePosition.y); if(f.hasMouthPosition) NSLog(@"Mouth %g %g\n", f.mouthPosition.x, f.mouthPosition.y); }
注意,检测到的位置是脸部数据在图片上的坐标(在uiimage上的,不是uiimageview上的),如果需要在视图上绘制范围,则需要进行坐标转换(y轴方向相反),并且也要注意图片在视图上的缩放等。
时间: 2024-11-16 14:18:56