Created
March 17, 2022 20:16
-
-
Save jb-apps/3a59585c2d550bb0afa4ec5f24e43524 to your computer and use it in GitHub Desktop.
A Face Detector using Vision
This file contains hidden or 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
import Vision | |
import AppKit | |
final class FaceDetector { | |
private enum Error: Swift.Error { | |
case couldNotFindFace | |
case couldNotGetCIImage | |
case couldNotProcessImageRequest | |
case didNotGetAnyObservation | |
} | |
private let faceDetectionRequest = VNSequenceRequestHandler() | |
func detectFace(in image: CGImage) async throws -> FaceParameters { | |
try await withCheckedThrowingContinuation { continuation in | |
detectFaceWrapper(on: image) { result in | |
continuation.resume(with: result) | |
} | |
} | |
} | |
private func detectFaceWrapper(on image: CGImage, completion: @escaping (Result<FaceParameters, Swift.Error>) -> Void) { | |
let faceDetection = VNDetectFaceRectanglesRequest() | |
DispatchQueue.global(qos: .userInteractive).async { | |
do { | |
try self.faceDetectionRequest.perform([faceDetection], on: image) | |
if | |
let result = faceDetection.results?.first, | |
let yaw = result.yaw?.doubleValue, | |
let pitch = result.pitch?.doubleValue, | |
let roll = result.roll?.doubleValue | |
{ | |
let parameters = FaceParameters( | |
yaw: Utilities.rad2deg(yaw), | |
roll: Utilities.rad2deg(roll), | |
pitch: Utilities.rad2deg(pitch)) | |
completion(.success(parameters)) | |
} else { | |
completion(.failure(Error.didNotGetAnyObservation)) | |
} | |
} catch { | |
completion(.failure(Error.couldNotProcessImageRequest)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment