从照片图像中选择并裁剪面部图像(ios)

时间:2017-01-21 12:21:58

标签: ios objective-c xcode core-image

我正试图从照片中获取裁剪的图像。我有以下代码来裁剪从ios人脸检测sdk获得的图像:

- (UIImage *)scaleAndRotateImage:(CIFeature *)ciFeature image:(UIImage *)image {
    static int kMaxResolution = 640;

    CGImageRef imgRef = image.CGImage;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
        } else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }

    CGFloat scaleRatio = bounds.size.width / width;

    UIImageOrientation orient = image.imageOrientation;
    switch(orient) {
        case UIImageOrientationUp:
            transform = CGAffineTransformIdentity;
            break;
                default:
            [NSException raise:NSInternalInconsistencyException
                        format:@"Invalid image orientation"];
    }

    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    } else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    CGContextConcatCTM(context, transform);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *returnImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return returnImage;
}

但是我怎样才能裁剪图像中的脸部(如框中的脸部图像),因为现在它会改变图像的原始分辨率?

1 个答案:

答案 0 :(得分:0)

如果你想用更方便和更多用户定义来裁剪图像,我建议你使用RSKImageCropper,它的github位置在这里:https://github.com/ruslanskorb/RSKImageCropper

因为你想裁剪面部的位置,所以系统的默认方法不能满足你的要求,你可以从这里学到:https://developer.apple.com/library/content/documentation/AudioVideo/Conceptual/CameraAndPhotoLib_TopicsForIOS/Articles/PickinganItemfromthePhotoLibrary.html#//apple_ref/doc/uid/TP40010408-SW1

Core Graphic的裁剪图像方法:CGImageCreateWithImageInRect,不容易确认你想要的矩形,因为你要获得面部位置你应该做很多工作,RSKImageCropper可能是你方便的选择。