Skip to content

Instantly share code, notes, and snippets.

@sgl0v
Created June 2, 2021 19:21
Show Gist options
  • Save sgl0v/b51255c3d1bd01ba05fadc149cbb448b to your computer and use it in GitHub Desktop.
Save sgl0v/b51255c3d1bd01ba05fadc149cbb448b to your computer and use it in GitHub Desktop.
extension ImageScanner {
private func detectRectangle(on image: CIImage, orientation: CGImagePropertyOrientation) -> Result<VNRectangleObservation, Error> {
var result: Result<VNRectangleObservation, Error> = .failure(ImageProviderError.internalError)
let semaphore = DispatchSemaphore(value: 1) // ➊
let rectanglesRequest = VNDetectRectanglesRequest { request, error in // ➋
guard error == nil,
let observations = request.results as? [VNRectangleObservation],
let detectedRectangle = observations.first else {
return
}
result = .success(detectedRectangle)
semaphore.signal()
}
let handler = VNImageRequestHandler(ciImage: image, orientation: orientation) // ➌
if (try? handler.perform([rectanglesRequest])) != nil { semaphore.wait() } // ➍
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment