VNDetectFaceRectanglesRequest未调用completionHandler

时间:2018-04-26 21:08:13

标签: swift face-detection apple-vision

我试图检测脸部。它无法检测,因为未调用handleFaces。我想知道为什么不调用它以及如果我想检测到脸,我该如何解决。

faceDetectionRequest = VNDetectFaceRectanglesRequest(completionHandler: self.handleFaces)

func handleFaces(request: VNRequest, error: Error?) {
    DispatchQueue.main.async {
        //perform all the UI updates on the main queue
        guard let results = request.results as? [VNFaceObservation] else { return }
        self.myView.removeMask()
        for face in results {
            self.myView.drawFaceboundingBox(face: face)
        }
    }
}

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我认为您应该以请求为参数在处理程序上调用perform,以执行检测。如果您有静态图片,我认为这可能有效:

import UIKit
import Vision

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let faceDetectionRequest = VNDetectFaceRectanglesRequest(completionHandler: self.handleFaces)
        guard let image = UIImage(named: "sample") else { return }
        guard let cgImage = image.cgImage else { return }
        let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
        do {
            try handler.perform([faceDetectionRequest])
        } catch let reqErr {
            print("Failed to perform request:", reqErr)
        }
    }

    func handleFaces(request: VNRequest, error: Error?) {
        DispatchQueue.main.async {
            //perform all the UI updates on the main queue
            guard let results = request.results as? [VNFaceObservation] else { return }
            self.myView.removeMask()
            for face in results {
                self.myView.drawFaceboundingBox(face: face)
            }
        }
    }
}

我必须赞扬“让我们来构建那个应用程序”中的Brian Voong编写代码:https://www.letsbuildthatapp.com/course_video?id=1572