2016-12-20 74 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

但是它沒有檢測到你會更新什麼? –