如何使用 CIDetector 和 Swift 在图像中裁剪检测到的矩形

How to crop detected rectangle in Image with CIDetector and Swift

我正在开发一个检测身份证的应用程序,我正在尝试使用 ios 中内置的 CIDetector 在实时预览中检测矩形对象。我在这里使用本教程中解释的解决方案 CoreImage Detectors

我得到了流畅的结果 image

我的问题:有没有办法提取和裁剪检测到的矩形?

func cropBusinessCardForPoints(image: CIImage, topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {

    var businessCard: CIImage
    businessCard = image.imageByApplyingFilter(
        "CIPerspectiveTransformWithExtent",
        withInputParameters: [
            "inputExtent": CIVector(CGRect: image.extent),
            "inputTopLeft": CIVector(CGPoint: topLeft),
            "inputTopRight": CIVector(CGPoint: topRight),
            "inputBottomLeft": CIVector(CGPoint: bottomLeft),
            "inputBottomRight": CIVector(CGPoint: bottomRight)])
    businessCard = image.imageByCroppingToRect(businessCard.extent)

    return businessCard
}

Swift3、简单的解决方法

let faceScanningArea = CGRect(x: 0, y: 0, width: 50, height: 50)

theFaceFrame.image = UIImage( cgImage( orginalImage.image?.cgImage )!.cropping(to: faceScanningArea)!)