2017-09-14 28 views
0

使用以下代码从图像中检测人脸。如何在Swift中执行人脸检测

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

+0

所以,'CIFeature'有一个'bounds'属性,它定义的边界矩形发现了什么。那么问题就变成了“你如何复制一部分图像”?对[这个问题](https://stackoverflow.com/questions/31254435/how-to-select-a-portion-of-an-image-crop-and-save-it-using-swift)可能会舍弃一些光(我个人喜欢顶级投票的答案),然后你可以看看[如何使用UIImagePNGRepresentation将UIImage保存到文件](https://www.hackingwithswift.com/example-code/media/how-to -save-a-uiimage-to-a-file-using-uiimagepngrepresentation) – MadProgrammer

+0

OSX没有任何UI。他还需要从NSImage转换为CIImage并返回到NSImage –

回答

5

的Xcode 9•夫特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

+0

感谢您的回答..我如何调整裁剪窗口的大小?即:获取检测到的面部矩形,增加矩形的大小并裁剪该部分。是否使用自定义矩形帮助更改'$ 0.bounds' ..请指教。 – techno

+0

@techno答案在我关闭另一个问题时与我联系的iOS问题。你可以使用'bounds.insetBy(dx:-10,dy:-10)' –

+1

非常感谢...... :) – techno