2012-02-23 126 views
8

我想写一个例程,需要一个UIImage并返回一个新的UIImage,只包含脸部。这看起来很简单,但是我的大脑在CoreImage和UIImage空间中遇到问题。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; 
} 

时返回从翻转图像的图像。我试着用这样的调整faceFeature.bounds

CGAffineTransform t = CGAffineTransformMakeScale(1.0f,-1.0f); 
CGRect newRect = CGRectApplyAffineTransform(faceFeature.bounds,t); 

...但是,让我产生的图像之外。

我确定有一些简单的方法可以解决这个问题,但是很少计算自下而上,然后使用X作为新的矩形,是否有一种“正确”的方式来做到这一点?

谢谢!

回答

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); 

这工作的魅力。

+5

我正在研究同样的事情,你能解释你为y轴执行的计算吗?什么是'最大的面'? – 2012-08-20 13:52:08

0

有没有简单的方法来实现这一目标,问题是来自iPhone相机的图像总是处于肖像模式,并且元数据设置用于使它们正确显示。如果事先告知图像的旋转,您还可以在脸部侦测呼叫中获得更好的准确性。只是为了使事情变得复杂,你必须以EXIF格式传递图像方向。

幸运的是,覆盖了所有的这家名为Squarecam苹果样本项目,我建议你检查它的细节

+0

是的,我已经适应了图像的旋转。我的问题与UIImage和CG例程的不同来源有关。 – 2012-02-23 22:50:40

5

只需使用CIContext从图像中裁剪出你的脸就更容易,也更简单。事情是这样的:

CGImageRef cgImage = [_ciContext createCGImage:[CIImage imageWithCGImage:inputImage.CGImage] fromRect:faceFeature.bounds]; 
UIImage *croppedFace = [UIImage imageWithCGImage:cgImage]; 

inputImage的是你的UIImage对象和faceFeature对象的类型CIFaceFeature你从得到的[CIDetector featuresInImage:]方法。