techno
techno

Reputation: 6508

How do I perform Face Detection in Swift

Im using the following code to detect a face from an image.

let userDirectory = FileManager.default.homeDirectoryForCurrentUser
let desktopDirectory = userDirectory.appendingPathComponent("Desktop")
let pictureUrl = desktopDirectory.appendingPathComponent("test").appendingPathExtension("jpg")

let image = CIImage(contentsOf: pictureUrl)   
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])
let faces = faceDetector?.features(in: image!) as! [CIFaceFeature]
print("Number of faces: \(faces.count)")

How can I detect a face and save it to an NSImage?

Upvotes: 0

Views: 1276

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236508

Xcode 9 • Swift 4

extension NSImage {
    var ciImage: CIImage? {
        guard let data = tiffRepresentation else { return nil }
        return CIImage(data: data)
    }
    var faces: [NSImage] {
        guard let ciImage = ciImage else { return [] }
        return (CIDetector(ofType: CIDetectorTypeFace, context: nil, options: [CIDetectorAccuracy: CIDetectorAccuracyHigh])?
            .features(in: ciImage) as? [CIFaceFeature])?
            .map {
                let ciimage = ciImage.cropped(to: $0.bounds)  // Swift 3 use cropping(to:)
                let imageRep = NSCIImageRep(ciImage: ciimage)
                let nsImage = NSImage(size: imageRep.size)
                nsImage.addRepresentation(imageRep)
            return nsImage
        }  ?? []
    }
}

Testing

let image = NSImage(contentsOf: URL(string: "https://i.sstatic.net/Xs4RX.jpg")!)!
let faces = image.faces

enter image description here

Upvotes: 5

Related Questions