UIImage人脸检测

Tim*_*van 8 xcode core-graphics face-detection ios

我正在尝试编写一个带有UIImage的例程,并返回一个只包含face的新UIImage.这看起来非常简单,但是我的大脑在绕过CoreImage和UIImage空间时遇到了问题.

这是基础知识:

- (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    return newImage;
}


-(UIImage *)getFaceImage:(UIImage *)picture {
  CIDetector  *detector = [CIDetector detectorOfType:CIDetectorTypeFace 
                                             context:nil 
                                             options:[NSDictionary dictionaryWithObject: CIDetectorAccuracyHigh forKey: CIDetectorAccuracy]];

  CIImage *ciImage = [CIImage imageWithCGImage: [picture CGImage]];
  NSArray *features = [detector featuresInImage:ciImage];

  // For simplicity, I'm grabbing the first one in this code sample,
  // and we can all pretend that the photo has one face for sure. :-)
  CIFaceFeature *faceFeature = [features objectAtIndex:0];

  return imageFromImage:picture inRect:faceFeature.bounds;
}
Run Code Online (Sandbox Code Playgroud)

返回的图像来自翻转图像.我试过faceFeature.bounds用这样的东西调整:

CGAffineTransform t = CGAffineTransformMakeScale(1.0f,-1.0f);
CGRect newRect = CGRectApplyAffineTransform(faceFeature.bounds,t);
Run Code Online (Sandbox Code Playgroud)

......但这给了我图像之外的结果.

我确定有一些简单的方法可以解决这个问题,但是如果没有计算自下而上,然后使用它作为X创建一个新的rect,是否有"正确"的方法来做到这一点?

谢谢!

jla*_*lar 5

使用CIContext从图像中裁剪脸部会更容易,也不那么麻烦.像这样的东西:

CGImageRef cgImage = [_ciContext createCGImage:[CIImage imageWithCGImage:inputImage.CGImage] fromRect:faceFeature.bounds];
UIImage *croppedFace = [UIImage imageWithCGImage:cgImage];
Run Code Online (Sandbox Code Playgroud)

其中inputImage是您的UIImage对象,faceFeature对象是您从[CIDetector featuresInImage:]方法获得的CIFaceFeature类型.


Tim*_*van 3

由于似乎没有一个简单的方法可以做到这一点,我只是编写了一些代码来做到这一点:

CGRect newBounds = CGRectMake(faceFeature.bounds.origin.x, 
                              _picture.size.height - faceFeature.bounds.origin.y - largestFace.bounds.size.height, 
                              faceFeature.bounds.size.width, 
                              faceFeature.bounds.size.height);
Run Code Online (Sandbox Code Playgroud)

这很有魅力。

  • 我正在研究同样的事情,您能解释一下您对 y 轴执行的计算吗?什么是“最大脸”? (5认同)