如何在Swift中执行人脸检测

时间:2017-09-14 04:34:37

标签: swift macos

我使用以下代码从图像中检测到脸部。

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)")

如何检测面部并将其保存到NSImage?

1 个答案:

答案 0 :(得分:5)

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
        }  ?? []
    }
}

测试

let image = NSImage(contentsOf: URL(string: "https://i.stack.imgur.com/Xs4RX.jpg")!)!
let faces = image.faces

enter image description here