interestingibis
4/25/2020 - 12:31 PM

Face Detection

private func detectFaces(completion: @escaping ([VNFaceObservation]?) -> Void) {
        
        guard let image = UIImage(named: photos[currentIndex]),
            let cgImage = image.cgImage,
            let orientation = CGImagePropertyOrientation(rawValue: UInt32(image.imageOrientation.rawValue)) else { return completion(nil) }
        
        let request = VNDetectFaceRectanglesRequest()
        let handler = VNImageRequestHandler(cgImage: cgImage, orientation: orientation, options: [:])
        
        DispatchQueue.global().async {
            
            try? handler.perform([request])
            
            guard let observations = request.results as? [VNFaceObservation] else { return completion(nil) }
            
            completion(observations)
            
        }