【问题标题】:How do I perform Face Detection in Swift如何在 Swift 中执行人脸检测
【发布时间】:2018-02-22 22:28:03
【问题描述】:

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

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?

【问题讨论】:

  • 所以,CIFeature 有一个 bounds 属性,它定义了找到的边界矩形。所以问题变成了“你如何复制图像的一部分”? this question 可能会对此有所启发(我个人喜欢投票最多的答案),然后您可以查看 How to save a UIImage to a file using UIImagePNGRepresentation
  • OSX 没有 UIwhatever。他还需要从 NSImage 转换为 CIImage 再转换回 NSImage

标签: swift macos


【解决方案1】:

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

【讨论】:

  • 感谢您的回答.. 如何调整裁剪窗口的大小?即:获取检测到的人脸矩形,增加矩形的大小并裁剪该部分。是否使用自定义矩形帮助更改$0.bounds。请建议。
  • @techno 答案是我在关闭您的其他问题时链接的 iOS 问题。你可以使用bounds.insetBy(dx: -10, dy: -10)
  • 非常感谢... :)
  • 在检测到的位图上绘制文本时,使用 cropping.tobounds.insetBy 会产生不正确的结果。
  • @techno 这与该代码无关。抱歉,伙计,我现在没时间问这个问题。
猜你喜欢
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 2016-03-26
  • 2019-11-18
  • 1970-01-01
  • 2013-07-03
  • 2013-09-24
  • 2020-06-28
相关资源
最近更新 更多