Created
June 2, 2021 19:21
-
-
Save sgl0v/7421859595af3c02cd5a6cdb7171b61a to your computer and use it in GitHub Desktop.
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 ImageScanner { | |
private func cropImage(_ inputImage: CIImage, with detectedRectangle: VNRectangleObservation) -> Result<UIImage, Error> { | |
let imageSize = inputImage.extent.size | |
let transform = CGAffineTransform.identity.scaledBy(x: imageSize.width, y: imageSize.height) | |
let boundingBox = detectedRectangle.boundingBox.applying(transform) | |
guard inputImage.extent.contains(boundingBox) else { | |
return .failure(ImageProviderError.internalError) | |
} | |
let topLeft = detectedRectangle.topLeft.applying(transform) | |
let topRight = detectedRectangle.topRight.applying(transform) | |
let bottomLeft = detectedRectangle.bottomLeft.applying(transform) | |
let bottomRight = detectedRectangle.bottomRight.applying(transform) | |
let correctedImage = inputImage.cropped(to: boundingBox) | |
.applyingFilter("CIPerspectiveCorrection", parameters: [ | |
"inputTopLeft": CIVector(cgPoint: topLeft), | |
"inputTopRight": CIVector(cgPoint: topRight), | |
"inputBottomLeft": CIVector(cgPoint: bottomLeft), | |
"inputBottomRight": CIVector(cgPoint: bottomRight) | |
]) | |
.transformed(by: CGAffineTransform.identity.rotated(by: 90 / 180.0 * CGFloat.pi)) | |
let imageRef = CIContext().createCGImage(correctedImage, from: correctedImage.extent)! | |
return .success(UIImage(cgImage: imageRef)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment