ying pod
ying pod

Reputation: 31

VNDetectFaceRectanglesRequest is not calling completionHandler

I'm trying to detect face. It can not detect because handleFaces is not called. I would like to know why is it not called and how I can solve if I would like to detect face.

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)
        }
    }
}

Please help me to solve this.

Upvotes: 3

Views: 1299

Answers (1)

Giorgio Tempesta
Giorgio Tempesta

Reputation: 2059

I think you should call perform on a handler with the requests as a parameter in order to perform the detection. If you have a static image I think this could work:

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)
            }
        }
    }
}

I have to give credit to Brian Voong from Let's Build That App for the code: https://www.letsbuildthatapp.com/course_video?id=1572.

Upvotes: 1

Related Questions