Core Image 实现面部识别

作者:Gregg Mojica 翻译:BigNerdCoding。 已将原文部分代码修改为 Swift3 ,有问题一起讨论。原文链接

Core Image 作为功能强大 Cocoa Touch 框架自带的组件,是 iOS SDK 中不可或缺的重要组成部分。然而,大多数情况下它却总在被开发者选择性忽视。 在这篇教程中,我们将会介绍其中的面部识别功能,以及如何在开发过程中使用该功能。

接下来的内容

面部识别功能早在 2011 年 iOS5 发布的时候就已经存在了,但是该功能并没有引起太多的关注。面部识别 API 除了让开发者检测脸部是否存在外,还可以更加细致的检测是否在微笑、闭眼。

首先,我们会创建一个简单应用并使用面部识别 API 将图片中的脸部区域使用方块高亮标记。在第二个示例中,我们将通过创建一个应用程序来查看更详细 API 使用方法,该应用程序允许用户拍摄照片,检测面部是否存在以及获取用户的面部坐标。 通过这些示例,我们将学习所有关于 iOS 面部检测的内容,以及如何利用这个强大,但又被遗忘在角落里的 API。

紧跟步伐,往下看!

配置工程项目

下载初始工程并用 XCode 打开,工程中除了一个 storyboard 并且绑定了一个 imageView 到 IBOutlet 别无其他。

在开始面部检测前,我们需要导入 Core Image 的类库。打开 ViewController.swift 文件并添加如下代码:

import CoreImage

开始面部识别

在初始工程中我们有一个 IBOutlet 的 imageView 变量,并且该变量已经与 storyboard 建立了连接。接下来我们编写面部识别的代码。直接复制下面代码到文件中,后面会有详细分析。

func detect() {
    
    guard let personciImage = CIImage(image: personPic.image!) else {
        return
    }
    
    let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
    let faceDetector = CIDetector(ofType: CIDetectorTypeFace,context: nil,options: accuracy)
    let faces = faceDetector!.features(in: personciImage)
    
    for face in faces as! [CIFaceFeature] {
        
        print("Found bounds are \(face.bounds)")
        
        let faceBox = UIView(frame: face.bounds)
        
        faceBox.layer.borderWidth = 3
        faceBox.layer.borderColor = UIColor.red.cgColor
        faceBox.backgroundColor = UIColor.clear
        personPic.addSubview(faceBox)
        
        if face.hasLeftEyePosition {
            print("Left eye bounds are \(face.leftEyePosition)")
        }
        
        if face.hasRightEyePosition {
            print("Right eye bounds are \(face.rightEyePosition)")
        }
    }
}

我们来看看上面的代码作了些什么:

  • 第3行:使用 personPic 视图中的图片创建了 CIImage 对象。

  • 第7行:设置识别的准确度 accuracy 为 CIDetectorAccuracyHigh。 您可以从CIDetectorAccuracyHigh(提供高处理能力)和CIDetectorAccuracyLow(提供低处理能力)中选择合适的准确度。 对于本文而言,我们选择CIDetectorAccuracyHigh,因为我们想要高精度。

  • 第8行:使用 accuracy 创建 CIDetector 对象。

  • 第9行:调用 faceDetector 对象上的 featuresInImage 函数,获取图片中所有的面部。

  • 第11行:遍历 faces 数组并将数组中的变量转为 CIFaceFeature

  • 第15行:创建 UIView 类型变量 faceBox,用于高亮识别的区域。

  • 第17行:设置 faceBox 的边框宽度。

  • 第18行:设置 faceBox 的边框颜色。

  • 第19行:设置 faceBox 的背景颜色为 clear

  • 第20行:将 faceBox 作为子视图加入到 personPic 视图中。

  • 22~28行:除了可以进行面部检测外,我们还可以检测面部中的左眼和右眼。这段代码只是演示 CIFaceFeature 中部分属性的使用所有也就没有进行高亮。

接下来我们直接在 viewDidLoad 中调用 detect 函数,添加以下代码:

detect()

运行程序你可能看到如下结果:

看起来不太正确,但是查看控制台的打印结果又好像检测到了。

Found bounds are (177.0,415.0,380.0,380.0)

造成这种现象的原因是我们还有一些细节问题未处理:

  • 面部识别功能是在原图上进行的,而该图片可能分辨率非常高,所以我们需要将原图和视图之间进行大小拟合。检测到的区域需要重新计算转换为视图中的位置。

  • 另一个重要的细节是:Core Image 和 UIView 的坐标系统不一致。我们需要对坐标系进行转换,以保障位置计算是的参照是一致的。

为了解决上诉两个细节问题,我们将 detect() 函数中的代码替换为:

func detect() {
    
    guard let personciImage = CIImage(image: personPic.image!) else {
        return
    }
    
    let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
    let faceDetector = CIDetector(ofType: CIDetectorTypeFace,options: accuracy)
    let faces = faceDetector!.features(in: personciImage)
    
    // For converting the Core Image Coordinates to UIView Coordinates
    // 计算坐标转换的矩阵,先对称后平移
    let ciImageSize = personciImage.extent.size
    var transform = CGAffineTransform.init(scaleX: 1,y: -1)

    transform = transform.translatedBy(x: 0,y: -ciImageSize.height)
    
    for face in faces as! [CIFaceFeature] {
        
        print("Found bounds are \(face.bounds)")
        
        // Apply the transform to convert the coordinates
        // 坐标转换
        var faceViewBounds = face.bounds.applying(transform)

        
        // Calculate the actual position and size of the rectangle in the image view
        // 坐标系重新映射完成后,计算是视图中的位置和偏移
        let viewSize = personPic.bounds.size
        let scale = min(viewSize.width / ciImageSize.width,viewSize.height / ciImageSize.height)
        let offsetX = (viewSize.width - ciImageSize.width * scale) / 2
        let offsetY = (viewSize.height - ciImageSize.height * scale) / 2
        
        faceViewBounds = faceViewBounds.applying(CGAffineTransform.init(scaleX: scale,y: scale))
        
       
        faceViewBounds.origin.x += offsetX
        faceViewBounds.origin.y += offsetY
        
        let faceBox = UIView(frame: faceViewBounds)
        
        faceBox.layer.borderWidth = 3
        faceBox.layer.borderColor = UIColor.red.cgColor
        faceBox.backgroundColor = UIColor.clear
        personPic.addSubview(faceBox)
        
        if face.hasLeftEyePosition {
            print("Left eye bounds are \(face.leftEyePosition)")
        }
        
        if face.hasRightEyePosition {
            print("Right eye bounds are \(face.rightEyePosition)")
        }
    }
}

代码中发生改变的地方已经备注了:首先我们计算得到进行坐标转换的矩阵,然后我们进行坐标后计算出原图中的识别区域映射在视图中的正确位置。

现在再次运行程序的话,你就能看见高亮区域正好就在我们希望的位置。

创建带面部识别的照相 App

想象一下你有一个相机/照片应用程序拍摄照片。 一旦拍摄完成,就检测图片中是否存在脸部。 如果存在的话,你就可以用一些标签来对该照片进行分类,反之亦然。 虽然本文中的目的不是创建一个照片存储的应用,但是接下来还是会编写一个实时相机应用程序来进一步研究面部识别 API 的一些细节。 为此,我们需要集成 UIImagePicker ,并在拍摄照片后立即运行我们的 Face Detection 代码。

在初始工程中我们已经创建了 CameraViewController 类,接下来我们丰富其中的代码:

class CameraViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    let imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()

        imagePicker.delegate = self
    }

    @IBAction func takePhoto(_ sender: AnyObject) {
        if !UIImagePickerController.isSourceTypeAvailable(.camera) {
            return
        }
    
        imagePicker.allowsEditing = false
        imagePicker.sourceType = .camera
    
        present(imagePicker,animated: true,completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            imageView.contentMode = .scaleAspectFit
            imageView.image = pickedImage
        }
        dismiss(animated: true,completion: nil)
        detect()
    
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true,completion: nil)
    }
    
}

首先,我们完成了 UIImagePicker 的代理设置。然后我们在代理方法 didFinishPickingMediaWithInfo 中图片赋值给了 imageView。最后我们让拍照视图消失并调用 detect() 对面部进行识别。

上面的 detect() 的实现如下:

func detect() {

    let imageOptions =  NSDictionary(object: NSNumber.init(value: 5),forKey: CIDetectorImageOrientation as NSString)
    let personciImage = CIImage(cgImage: imageView.image!.cgImage!)
    
    let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
    let faceDetector = CIDetector(ofType: CIDetectorTypeFace,options: accuracy)
    let faces = faceDetector!.features(in: personciImage,options: imageOptions as? [String : AnyObject])
    
    
    if let face = faces.first as? CIFaceFeature {
        print("found bounds are \(face.bounds)")
        
        let alert = UIAlertController(title: "Say Cheese!",message: "We detected a face!",preferredStyle: .alert)
        
        alert.addAction(UIAlertAction.init(title: "OK",style: .default,handler: nil))
        
        present(alert,completion: nil)
       
        
        if face.hasSmile {
            print("face is smiling");
        }
        
        if face.hasLeftEyePosition {
            print("Left eye bounds are \(face.leftEyePosition)")
        }
        
        if face.hasRightEyePosition {
            print("Right eye bounds are \(face.rightEyePosition)")
        }
    } else {
        let alert = UIAlertController(title: "No Face!",message: "No face was detected",preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK",handler: nil))
        present(alert,completion: nil)
    }
}

此处的 detect() 函数实现和之前的哪个类似,只不过添加了识别结果的提示信息展示功能。

CIFaceFeature 对象已经内置了多个属性和方法来帮助我们处理更加细节性的问题。例如用 .hasSmile 来检测用户的笑容,.hasLeftEyePosition.hasRightEyePosition 来检查左右眼(当然,我们希望一切都是完美的)。

另外我们也可以通过 hasMouthPosition 属性来检查图片中是否存在嘴巴,并且在存在的情况下访问 mouthPosition 属性来获取位置。代码如下:

if (face.hasMouthPosition) {
    print("mouth detected")
}

如你所见,使用 Core Image 框架完成面部检测是如此的简单。除了笑容、眼睛、嘴巴的检测之外,我们还可以通过 leftEyeClosedrightEyeClosed 来判断眼睛是不是闭着的。

总结

本文我们研究了 Core Image 框架中面部识别相关的 API,并且成功将其应用到了照相应用中。该 API 功能强大且使用简单,我希望这篇文章能让你对这个被忽视的有一些新的认识。

完整参考代码地址

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...