Norris
Norris

Reputation: 5

Swift 4 - How to check if the eyes are closed

I use Core Image to detect the face, it also success,

but I can't detect the eyes are closed. :(

I want to detect the face and check if the eyes are closed, thank you very much!!

code:

    func detect(ciimage:CIImage) {
    let imageOptions =  NSDictionary(object: NSNumber(value: 5) as NSNumber, forKey: CIDetectorImageOrientation as NSString)
    let personciImage = ciimage
    let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
    let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy)
    let faces = faceDetector?.features(in: personciImage, options: imageOptions as? [String : AnyObject])

    //success
    if let face = faces?.first as? CIFaceFeature {


        hasFace = true

        // face.leftEyeClosed not work,It always outputs false
        if face.leftEyeClosed {
            lefteyeclosed = true
        }else{
            lefteyeclosed = false
        }

        // face.leftEyeClosed not work
        if face.rightEyeClosed{
            lefteyeclosed = true
        }else{
            lefteyeclosed = false
        }
    } else {
        hasFace = false
    }
}

I modified the following code:

    let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh]
    let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy)
    let faces = faceDetector?.features(in: ciimage, options: [CIDetectorEyeBlink : true, CIDetectorImageOrientation: 5])

Upvotes: 0

Views: 1677

Answers (1)

Sulthan
Sulthan

Reputation: 130092

From the leftEyeClosed documentation:

For closed eyes to be detected, the key CIDetectorEyeBlink must be present with a value of true in the dictionary passed to a detector’s features(in:options:) method.

Therefore, your options should be:

let options = [
   CIDetectorAccuracy: CIDetectorAccuracyHigh,
   CIDetectorEyeBlink: true
]
let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: options)

Upvotes: 1

Related Questions