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的效果很不错,只有在人物的图片上显示了标记。