使用相机会话拍摄的裁剪图像

我正在尝试裁剪具有特定关注区域的相机拍摄的图像。为了找到比例作物矩形,我使用previewLayer.metadataOutputRectConverted方法。但是裁剪后我得到了错误的比率。

调试示例:

(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

使用相机会话拍摄的裁剪图像

如您所见,我希望裁剪的图像比例将是~0.79,与我用于裁剪的rectOfInterest一样。

方法:

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

目标矩形:

使用相机会话拍摄的裁剪图像

qiyugfh0715021 回答:使用相机会话拍摄的裁剪图像

我不是专家,但是我认为您误解了metadataOutputRectConverted方法的用法。 您的代码不可能以相同的长宽比返回裁剪后的图像,因为您相互之间(实际上是互不相干的数字)相互乘积(我认为是这样)。

您可以尝试此方法

previewLayer.layerRectConverted(fromMetadataOutputRect: CGRect(x: 0,y: 0,width: 1,height: 1))

要了解由metadataOututRectConverted进行的实际计算是什么。

我认为您可以更好地解释您想要实现的目标,并可能提供一个示例项目(或者至少提供一些有关您使用的实际图像/矩形的上下文),以帮助我们进行调试(如果需要)对此有更多帮助。

,

感谢@Enricoza,我了解如何解决我的问题。这是代码:

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

        let metadataOutputRect = CGRect(x: 0,height: 1)
        let outputRect = previewLayer.layerRectConverted(fromMetadataOutputRect: metadataOutputRect)

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

        let width = image.size.width
        let height = image.size.height

        let factorX = width / outputRect.width
        let factorY = height / outputRect.height
        let factor = max(factorX,factorY)

        let cropRect = CGRect(x: (rectOfInterest.origin.x - outputRect.origin.x) * factor,y: (rectOfInterest.origin.y - outputRect.origin.y) * factor,width: rectOfInterest.size.width * factor,height: rectOfInterest.size.height * factor)

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

        return UIImage(cgImage: cropped,scale: image.scale,orientation: image.imageOrientation)
    }
本文链接:https://www.f2er.com/3163964.html

大家都在问