Skip to content

Instantly share code, notes, and snippets.

@KaiCode2
Created October 9, 2016 20:06
Show Gist options
  • Save KaiCode2/b0f67bc2b7fd4931808d7819e0f3120f to your computer and use it in GitHub Desktop.
Save KaiCode2/b0f67bc2b7fd4931808d7819e0f3120f to your computer and use it in GitHub Desktop.
Facial Recognition using CIDetector.
import UIKit
import CoreImage
extension UIImage {
/** Returns an Array of all detected faces as *UIImages.* If none are found empty Array will be returned.
- Author: Kai Aldag
*/
func findFacesInImage() throws -> [UIImage] {
guard let image = UIKit.CIImage(image: self),
let detector = CIDetector(ofType: CIDetectorTypeFace,
context: nil,
options: nil) else { throw FacialRecognitionError.internalError }
let faces = detector.features(in: image)
let images: [UIImage] = faces.flatMap { feature -> UIImage? in
guard let face = feature as? CIFaceFeature,
let ciFaceImage = UIKit.CIImage(image: self)?.cropping(to: face.bounds)
else { return nil }
return UIImage(ciImage: ciFaceImage, scale: 0.9, orientation: imageOrientation)
}
return images
}
}
enum FacialRecognitionError: Error {
case internalError
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment