首页 文章

CIDetector透视和Swift裁剪

提问于
浏览
5

我在我的应用程序中实现了 CIDetector 以检测图像上的矩形,但现在我如何使用返回的 CGPoint 来裁剪图像以便我可以将其显示回来?

从视角我尝试应用CIPerspectiveCorrection过滤器,但无法使其工作 .

我已经四处寻找并发现了一些线索,但在Swift中找不到解决方案 .

如何使用 CIDetector (检测到的矩形)提供的数据来修复透视并裁剪图像?

对于那些可能不熟悉 CIDetectorTypeRectangle 返回的人:它返回4 CGPoint 的bottomLeft,bottomRight,topLeft,topRight .

1 回答

  • 8

    这是有效的:

    func flattenImage(image: CIImage, topLeft: CGPoint, topRight: CGPoint,bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {
    
        return image.applyingFilter("CIPerspectiveCorrection", withInputParameters: [
    
            "inputTopLeft": CIVector(cgPoint: topLeft),
            "inputTopRight": CIVector(cgPoint: topRight),
            "inputBottomLeft": CIVector(cgPoint: bottomLeft),
            "inputBottomRight": CIVector(cgPoint: bottomRight)
    
    
            ])
    
    }
    

    无论您在何处检测到矩形:

    UIGraphicsBeginImageContext(CGSize(width: flattenedImage!.extent.size.height, height: flattenedImage!.extent.size.width))
    
    UIImage(ciImage:resultImage!,scale:1.0,orientation:.right).draw(in: CGRect(x: 0, y: 0, width: resultImage!.extent.size.height, height: resultImage!.extent.size.width))
    
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    

相关问题