Skip to content

Instantly share code, notes, and snippets.

@ozgurshn
Created March 16, 2020 11:48
Show Gist options
  • Save ozgurshn/6e8c3ef26e30765f798878a1e47a6f53 to your computer and use it in GitHub Desktop.
Save ozgurshn/6e8c3ef26e30765f798878a1e47a6f53 to your computer and use it in GitHub Desktop.
Perspective transform to rectangle detected by Vision
guard let results = request.results as? [VNRectangleObservation] else {
fatalError("Unexpected result type from VNDetectRectanglesRequest")
}
// Need check results only if objectsCountToDetect isn't default
if objectsCountToDetect != defaultObjectsCount {
guard results.count == objectsCountToDetect else {
Logger.e("Wrong Rectangulars Results count: Founded - \(results.count) | Required - \(objectsCountToDetect)")
return
}
}
if isCancelled { return }
self.operationResult = results.compactMap { detectedRectangle in
let transform = CGAffineTransform.identity
.scaledBy(x: inputImage.extent.width, y: inputImage.extent.height)
let topLeft = detectedRectangle.topLeft.applying(transform)
let topRight = detectedRectangle.topRight.applying(transform)
let bottomLeft = detectedRectangle.bottomLeft.applying(transform)
let bottomRight = detectedRectangle.bottomRight.applying(transform)
var correctedImage = inputImage
.applyingFilter("CIPerspectiveCorrection", parameters: [
"inputTopLeft": CIVector(cgPoint: topLeft),
"inputTopRight": CIVector(cgPoint: topRight),
"inputBottomLeft": CIVector(cgPoint: bottomLeft),
"inputBottomRight": CIVector(cgPoint: bottomRight)
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment