Created
October 9, 2016 20:06
-
-
Save KaiCode2/b0f67bc2b7fd4931808d7819e0f3120f to your computer and use it in GitHub Desktop.
Facial Recognition using CIDetector.
This file contains 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 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