-->

如何从AVCapture裁剪图像以看到显示器上的矩形(How to crop an image fr

2019-08-21 22:23发布

这是推动我疯了,因为我无法得到它的工作。 我有以下情形:

我使用的是AVCaptureSessionAVCaptureVideoPreviewLayer创建自己的相机接口。 界面显示的矩形。 下面是AVCaptureVideoPreviewLayer充满整个屏幕。

我想在某种程度上被裁剪所拍摄的图像,所形成的图像显示在准确在显示器上看到RECT内容。

我的设置是这样的:

_session = [[AVCaptureSession alloc] init];
AVCaptureSession *session = _session;
session.sessionPreset = AVCaptureSessionPresetPhoto;

AVCaptureDevice *camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (camera == nil) {
    [self showImagePicker];
    _isSetup = YES;
    return;
}
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

captureVideoPreviewLayer.frame = self.liveCapturePlaceholderView.bounds;
[self.liveCapturePlaceholderView.layer addSublayer:captureVideoPreviewLayer];

NSError *error;
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:camera error:&error];
if (error) {
    HGAlertViewWrapper *av = [[HGAlertViewWrapper alloc] initWithTitle:kFailedConnectingToCameraAlertViewTitle message:kFailedConnectingToCameraAlertViewMessage cancelButtonTitle:kFailedConnectingToCameraAlertViewCancelButtonTitle otherButtonTitles:@[kFailedConnectingToCameraAlertViewRetryButtonTitle]];
    [av showWithBlock:^(NSString *buttonTitle){
        if ([buttonTitle isEqualToString:kFailedConnectingToCameraAlertViewCancelButtonTitle]) {
            [self.delegate gloameCameraViewControllerDidCancel:self];
        }
        else {
            [self setupAVSession];
        }
    }];
}
[session addInput:input];

NSDictionary *options = @{ AVVideoCodecKey : AVVideoCodecJPEG };
_stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
[_stillImageOutput setOutputSettings:options];

[session addOutput:_stillImageOutput];

[session startRunning];
_isSetup = YES;

我捕捉这样的形象:

[_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
 {
     if (error) {
         MWLogDebug(@"Error capturing image from camera. %@, %@", error, [error userInfo]);
         _capturePreviewLayer.connection.enabled = YES;
     }
     else
     {
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         UIImage *image = [[UIImage alloc] initWithData:imageData];

         CGRect cropRect = [self createCropRectForImage:image];
         UIImage *croppedImage;// = [self cropImage:image toRect:cropRect];
         UIGraphicsBeginImageContext(cropRect.size);
         [image drawAtPoint:CGPointMake(-cropRect.origin.x, -cropRect.origin.y)];
         croppedImage = UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
         self.capturedImage = croppedImage;
         [_session stopRunning];             
     }
 }];

createCropRectForImage:方法我已经试过各种方法来计算矩形切出图像的,但没有成功为止。

- (CGRect)createCropRectForImage:(UIImage *)image
{
    CGPoint maskTopLeftCorner = CGPointMake(self.maskRectView.frame.origin.x, self.maskRectView.frame.origin.y);
    CGPoint maskBottomRightCorner = CGPointMake(self.maskRectView.frame.origin.x + self.maskRectView.frame.size.width, self.maskRectView.frame.origin.y + self.maskRectView.frame.size.height);

    CGPoint maskTopLeftCornerInLayerCoords = [_capturePreviewLayer convertPoint:maskTopLeftCorner fromLayer:self.maskRectView.layer.superlayer];
    CGPoint maskBottomRightCornerInLayerCoords = [_capturePreviewLayer convertPoint:maskBottomRightCorner fromLayer:self.maskRectView.layer.superlayer];
    CGPoint maskTopLeftCornerInDeviceCoords = [_capturePreviewLayer captureDevicePointOfInterestForPoint:maskTopLeftCornerInLayerCoords];
    CGPoint maskBottomRightCornerInDeviceCoords = [_capturePreviewLayer captureDevicePointOfInterestForPoint:maskBottomRightCornerInLayerCoords];

    float x = maskTopLeftCornerInDeviceCoords.x * image.size.width;
    float y = (1 - maskTopLeftCornerInDeviceCoords.y) * image.size.height;
    float width = fabsf(maskTopLeftCornerInDeviceCoords.x - maskBottomRightCornerInDeviceCoords.x) * image.size.width;
    float height = fabsf(maskTopLeftCornerInDeviceCoords.y - maskBottomRightCornerInDeviceCoords.y) * image.size.height;

    return CGRectMake(x, y, width, height);
}

这就是我目前的版本,但即使没有得到正确的比例。 可能有人请帮助我!

我已经使用这种方法来裁剪我的形象也尝试:

- (UIImage*)cropImage:(UIImage*)originalImage toRect:(CGRect)rect{

    CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], rect);

    CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef);
    CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
    CGContextRef bitmap = CGBitmapContextCreate(NULL, rect.size.width, rect.size.height, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);

    if (originalImage.imageOrientation == UIImageOrientationLeft) {
        CGContextRotateCTM (bitmap, radians(90));
        CGContextTranslateCTM (bitmap, 0, -rect.size.height);

    } else if (originalImage.imageOrientation == UIImageOrientationRight) {
        CGContextRotateCTM (bitmap, radians(-90));
        CGContextTranslateCTM (bitmap, -rect.size.width, 0);

    } else if (originalImage.imageOrientation == UIImageOrientationUp) {
        // NOTHING
    } else if (originalImage.imageOrientation == UIImageOrientationDown) {
        CGContextTranslateCTM (bitmap, rect.size.width, rect.size.height);
        CGContextRotateCTM (bitmap, radians(-180.));
    }

    CGContextDrawImage(bitmap, CGRectMake(0, 0, rect.size.width, rect.size.height), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);

    UIImage *resultImage=[UIImage imageWithCGImage:ref];
    CGImageRelease(imageRef);
    CGContextRelease(bitmap);
    CGImageRelease(ref);

    return resultImage;
}

没有任何人有方法的“最佳组合”,使这项工作? :)

Answer 1:

我已经使用解决了这个问题metadataOutputRectOfInterestForRect功能。

它适用于任何方向。

[_stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection
                                               completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error)
 {
     if (error)
     {
         [_delegate cameraView:self error:@"Take picture failed"];
     }
     else
     {

         NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
         UIImage *takenImage = [UIImage imageWithData:jpegData];

         CGRect outputRect = [_previewLayer metadataOutputRectOfInterestForRect:_previewLayer.bounds];
         CGImageRef takenCGImage = takenImage.CGImage;
         size_t width = CGImageGetWidth(takenCGImage);
         size_t height = CGImageGetHeight(takenCGImage);
         CGRect cropRect = CGRectMake(outputRect.origin.x * width, outputRect.origin.y * height, outputRect.size.width * width, outputRect.size.height * height);

         CGImageRef cropCGImage = CGImageCreateWithImageInRect(takenCGImage, cropRect);
         takenImage = [UIImage imageWithCGImage:cropCGImage scale:1 orientation:takenImage.imageOrientation];
         CGImageRelease(cropCGImage);

     }
 }
 ];

该takenImage仍然imageOrientation相关的图像。 您可以删除进一步的图像处理方位信息。

UIGraphicsBeginImageContext(takenImage.size);
[takenImage drawAtPoint:CGPointZero];
takenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();


Answer 2:

在斯威夫特3:

private func cropToPreviewLayer(originalImage: UIImage) -> UIImage {
    let outputRect = previewLayer.metadataOutputRectOfInterest(for: previewLayer.bounds)
    var cgImage = originalImage.cgImage!
    let width = CGFloat(cgImage.width)
    let height = CGFloat(cgImage.height)
    let cropRect = CGRect(x: outputRect.origin.x * width, y: outputRect.origin.y * height, width: outputRect.size.width * width, height: outputRect.size.height * height)

    cgImage = cgImage.cropping(to: cropRect)!
    let croppedUIImage = UIImage(cgImage: cgImage, scale: 1.0, orientation: originalImage.imageOrientation)

    return croppedUIImage
}


Answer 3:

AVMakeRectWithAspectRatioInsideRect这个API是AVFoundation,它将返回裁剪区域给定作物尺寸的图像。



Answer 4:

斯威夫特4:

我宁愿从来没有强行拆开包装,以避免崩溃,所以我用自选和guards在我的。

private func cropToPreviewLayer(originalImage: UIImage) -> UIImage? {
    guard let cgImage = originalImage.cgImage else { return nil }

    let outputRect = previewLayer.metadataOutputRectConverted(fromLayerRect: previewLayer.bounds)

    let width = CGFloat(cgImage.width)
    let height = CGFloat(cgImage.height)
    let cropRect = CGRect(x: outputRect.origin.x * width, y: outputRect.origin.y * height, width: outputRect.size.width * width, height: outputRect.size.height * height)

    if let croppedCGImage = cgImage.cropping(to: cropRect) {
        return UIImage(cgImage: croppedCGImage, scale: 1.0, orientation: originalImage.imageOrientation)
    }

    return nil
}


文章来源: How to crop an image from AVCapture to a rect seen on the display