如何在Swift中执行人脸检测 [英] How do I perform Face Detection in Swift

查看:233
本文介绍了如何在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)")

如何检测人脸并将其保存到NSImage?

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

推荐答案

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.stack.imgur.com/Xs4RX.jpg")!)!
let faces = image.faces

这篇关于如何在Swift中执行人脸检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆