Friday, 8 November 2019

Crop image captured with camera session

I am trying to crop image captured with camera session with specific rect of interest. For find proportional crop rect I am using previewLayer.metadataOutputRectConverted method. But after cropping i got wrong ratio.

Debug example:

(lldb) po rectOfInterest.width / rectOfInterest.height
0.7941176470588235

(lldb) po image.size.width / image.size.height
0.75

(lldb) po outputRect.width / outputRect.height
0.9444444444444444

(lldb) po Double(cropped.width) / Double(cropped.height)
0.7080152671755725

Debug

As you can see, I am expecting that cropped image ratio will be ~0.79 as rectOfInterest which I am using for cropping.

Method:

private func makeImageCroppedToRectOfInterest(from image: UIImage) -> UIImage {
    let previewLayer = cameraController.previewLayer
    let rectOfInterest = layoutLayer.layoutRect

    let outputRect = previewLayer.metadataOutputRectConverted(fromLayerRect: rectOfInterest)

    guard let cgImage = image.cgImage else {
        return image
    }

    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)

    guard let cropped = cgImage.cropping(to: cropRect) else {
        return image
    }

    return UIImage(cgImage: cropped, scale: image.scale, orientation: image.imageOrientation)
}


from Crop image captured with camera session

No comments:

Post a Comment