Last active
August 5, 2024 16:27
-
-
Save StanDimitroff/ef745f559f7d1dd2258f47384a66c0c7 to your computer and use it in GitHub Desktop.
Image perspective correction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIImage { | |
var flattened: UIImage? { | |
let ciImage = CIImage(image: self)! | |
guard let openGLContext = EAGLContext(api: .openGLES2) else { return nil } | |
let ciContext = CIContext(eaglContext: openGLContext) | |
let detector = CIDetector(ofType: CIDetectorTypeRectangle, | |
context: ciContext, | |
options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])! | |
guard let rect = detector.features(in: ciImage).first as? CIRectangleFeature | |
else { return nil } | |
let perspectiveCorrection = CIFilter(name: "CIPerspectiveCorrection")! | |
perspectiveCorrection.setValue(CIVector(cgPoint: rect.topLeft), | |
forKey: "inputTopLeft") | |
perspectiveCorrection.setValue(CIVector(cgPoint: rect.topRight), | |
forKey: "inputTopRight") | |
perspectiveCorrection.setValue(CIVector(cgPoint: rect.bottomRight), | |
forKey: "inputBottomRight") | |
perspectiveCorrection.setValue(CIVector(cgPoint :rect.bottomLeft), | |
forKey: "inputBottomLeft") | |
perspectiveCorrection.setValue(ciImage, | |
forKey: kCIInputImageKey) | |
if let output = perspectiveCorrection.outputImage, | |
let cgImage = ciContext.createCGImage(output, from: output.extent) { | |
return UIImage(cgImage: cgImage, scale: scale, orientation: imageOrientation) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment