iOS - 将图像裁剪到检测到的面部时出现问题

标签 ios objective-c uiimage crop face-detection

我正在尝试将 UIImage 裁剪为已使用内置 CoreImage 人脸检测功能检测到的人脸。我似乎能够正确检测到人脸,但是当我尝试将 UIImage 裁剪到人脸的边界时,它远不正确。我的面部检测代码如下所示:

-(NSArray *)facesForImage:(UIImage *)image {
    CIImage *ciImage = [CIImage imageWithCGImage:image.CGImage];

    CIContext *context = [CIContext contextWithOptions:nil];
    NSDictionary *opts = @{CIDetectorAccuracy : CIDetectorAccuracyHigh};

    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeFace context:context options:opts];
    NSArray *features = [detector featuresInImage:ciImage];

    return features;
}

...裁剪图像的代码如下所示:

-(UIImage *)imageCroppedToFaceAtIndex:(NSInteger)index forImage:(UIImage *)image {
    NSArray *faces = [self facesForImage:image];
    if((index < 0) || (index >= faces.count)) {
        DDLogError(@"Invalid face index provided");

        return nil;
    }

    CIFaceFeature *face = [faces objectAtIndex:index];
    CGRect faceBounds = face.bounds;

    CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, faceBounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

    return croppedImage;
}

我有一张只有一张脸的图像用于测试,它似乎可以毫无问题地检测到它。但收成还差得很远。知道这段代码可能有什么问题吗?

最佳答案

对于其他有类似问题的人——将 CGImage 坐标转换为 UIImage 坐标——我找到了 this great article解释如何使用 CGAffineTransform 来完成我正在寻找的东西。

关于iOS - 将图像裁剪到检测到的面部时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24100733/

相关文章:

objective-c - 对于强集合实例,赋值给nil等于释放赋值给nil吗?

iOS 在呈现为模板的图像上使用默认颜色

ios - 当单词出现在数组标签中时设置图像

ios - TouchesMoved 与 UITouch

ios - NSDateFormatter 仍在解析而不是格式不正确

objective-c - 使用多个分隔符拆分 NSString?

objective-c - 分配指针 - Objective-C

ios - CollectionViewCell 无法识别的选择器发送到实例

ios - 文件路径中的可选 Swift3

ios - 如何将富文本粘贴到 UITextView 中?