2016-12-20 56 views
2

即使没有错误,此代码也不会显示相机中的人脸检测。 我希望脸部应该可以在红包的周围进行实时检测,但我认为我没有正确放置代码或在Viewdidload或其他位置放置什么东西?实时人脸检测不起作用

import UIKit 
import CoreImage 

class ViewController: UIViewController ,UIAlertViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { 

@IBOutlet var imageView: UIImageView! 
@IBAction func Moodify(_ sender: UIButton) { 


    func detect() { 

     guard let personciImage = CIImage(image: imageView.image!) else { 
      return 
     } 

     let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh] 
     let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, 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(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 = imageView.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(scaleX: scale, y: scale)) 
      faceViewBounds.origin.x += offsetX 
      faceViewBounds.origin.y += offsetY 

      let faceBox = UIView(frame: faceViewBounds) 
      //let faceBox = UIView(frame: face.bounds) 
      faceBox.layer.borderWidth = 3 
      faceBox.layer.borderColor = UIColor.red.cgColor 
      faceBox.backgroundColor = UIColor.clear 
      imageView.addSubview(faceBox) 

      if face.hasLeftEyePosition { 
       print("Left eye bounds are \(face.leftEyePosition)") 
      } 

      if face.hasRightEyePosition { 
       print("Right eye bounds are \(face.rightEyePosition)") 
      } 
     } 
    } 

    let picker = UIImagePickerController() 
    picker.delegate = self 
    picker.allowsEditing = true 
    picker.sourceType = .camera 
    picker.cameraDevice = .front 
    self.present(picker, animated: true, completion: { _ in }) 

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [AnyHashable: Any]) { 
     let chosenImage = info[UIImagePickerControllerEditedImage] 
     self.imageView!.image = chosenImage as? UIImage 
     picker.dismiss(animated: true, completion: { _ in }) 
    } 

    // picker.dismiss(animated: true, completion: { _ in }) 
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { 
     picker.dismiss(animated: true, completion: { _ in }) 
    } 
} 

override func viewDidLoad() { 

    let alert = UIAlertController(title: "Ooops!!!", message: "Camera is not connected", preferredStyle: UIAlertControllerStyle.alert) 
    alert.addAction(UIAlertAction(title: "Connect", style: UIAlertActionStyle.default, handler: nil)) 
    self.present(alert, animated: true, completion: nil) 

    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
} 
+0

请问您可以分享一下您从哪里获取此代码的教程? –

+0

@TungFam这里是链接:http://www.appcoda.com/face-detection-core-image/ –

+0

我不知道你是否以正确的方式问,但你说“这段代码不显示检测面对相机“。根据教程,它应该在图像上显示脸部,而不是实时显示在相机上。 –

回答

0

你很可能只需要触发功能的方式,它是如何在文档

我们将调用检测方法viewDidLoad中所述。因此,插入下面的代码行的方法:

override func viewDidLoad() { 
    super.viewDidLoad() 

    detect() 

}

编译并运行应用程序。

编辑: 这是解决方案,而功能“检测”是作为子类方法,但在你的情况下,你使用IBAction,它有不同的语法。你应该试着删除功能检测(),这架

} 

let picker = 

的名称,这部分必须为你的情况下,功能

let picker = UIImagePickerController() 
picker.delegate = self 
picker.allowsEditing = true 
picker.sourceType = .camera 
picker.cameraDevice = .front 
self.present(picker, animated: true, completion: { _ in }) 

里面你大概可以忽略这部分也是如此。

+0

使用未解析的标识符“detect”错误 –

+0

我也清理并运行了,但遇到了此错误 –

+0

@Solangi您使用的SWIFT版本是什么?在旧版本之前,需要使用self.detect() – Vanya

0

看完您的代码后,您在拍完照片后甚至没有打电话detect()。我试着按照下面的描述修复它,然而,detect()将返回零面,发现如我在Face Detection with Camera中所描述的那样。

lazy var picker: UIImagePickerController = { 
    let picker = UIImagePickerController() 
    picker.delegate = self 
    picker.allowsEditing = true 
    picker.sourceType = .camera 
    picker.cameraDevice = .front 
    return picker 
}() 

@IBOutlet var imageView: UIImageView! 
override func viewDidLoad() { 
    super.viewDidLoad() 
    imageView.contentMode = .scaleAspectFit 
} 

@IBAction func TakePhoto(_ sender: Any) { 
    self.present(picker, animated: true, completion: nil) 
} 

// MARK: - UIImagePickerControllerDelegate 
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
    if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage { 
     self.imageView!.image = chosenImage 
     // Got the image from camera, the imageView.image is not nil, so it's time for facial detection 
     detect() 
     picker.dismiss(animated: true, completion: nil) 
    } 
} 


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

// MARK: - Face Detection 

func detect() { 

    guard let personciImage = CIImage(image: imageView.image!) else { 
     return 
    } 

    let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh] 
    let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, 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(scaleX: 1, y: -1) 
    transform = transform.translatedBy(x: 0, y: -ciImageSize.height) 
    print("faces.count = \(faces?.count)") 

    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 = imageView.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(scaleX: scale, y: scale)) 
     faceViewBounds.origin.x += offsetX 
     faceViewBounds.origin.y += offsetY 

     let faceBox = UIView(frame: faceViewBounds) 
     //let faceBox = UIView(frame: face.bounds) 
     faceBox.layer.borderWidth = 3 
     faceBox.layer.borderColor = UIColor.red.cgColor 
     faceBox.backgroundColor = UIColor.clear 
     imageView.addSubview(faceBox) 

     if face.hasLeftEyePosition { 
      print("Left eye bounds are \(face.leftEyePosition)") 
     } 

     if face.hasRightEyePosition { 
      print("Right eye bounds are \(face.rightEyePosition)") 
     } 
    } 
} 
+0

尚未检测到!我也尝试在viewdidload中提到detect(),但它给出了错误的致命错误展开可选,当你更新答案时,你是否更新我问题代码中的更改? –

+0

当你在'viewDidLoad()'中调用'detect()'时会崩溃,因为imageView.image没有设置在开头 – WeiJay

+0

但是它没有检测到你会更新什么? –