CIFaceFeature仅检测一个面部

时间:2016-07-20 16:28:21

标签: swift xcode

问题是我的代码只适用于一个人脸。如果我拍摄两张脸的照片,它将无法检测到第二张脸,而对于两张脸则相同。这是我的代码:

if let inputImage = imageView.image {
        let ciImage = CIImage(CGImage: inputImage.CGImage!)

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

        let faces = faceDetector.featuresInImage(ciImage)

        if let face = faces.first as? CIFaceFeature {
            print("Found face at \(face.bounds)")

            if face.hasLeftEyePosition {
                print("Found left eye at \(face.leftEyePosition)")
            }

            if face.hasRightEyePosition {
                print("Found right eye at \(face.rightEyePosition)")
            }

            if face.hasMouthPosition {
                print("Found mouth at \(face.mouthPosition)")
            }
        }
        print("\(faces.count)")
    }

1 个答案:

答案 0 :(得分:0)

你的问题是你只能在找到的第一张脸上工作,因为:

if let face = faces.first as? CIFaceFeature {

因此,例如,您可以使用循环并迭代数组,如下所示:

for item in faces {
    if let face = item as? CIFaceFeature {
        print("Found face at \(face.bounds)")

        if face.hasLeftEyePosition {
            print("Found left eye at \(face.leftEyePosition)")
        }

        if face.hasRightEyePosition {
            print("Found right eye at \(face.rightEyePosition)")
        }

        if face.hasMouthPosition {
            print("Found mouth at \(face.mouthPosition)")
        }
    }
}

或者像这样,稍好一点:

if let faces = faceDetector.featuresInImage(ciImage) as? [CIFaceFeature] {
    for face in faces {
        print("Found face at \(face.bounds)")

        if face.hasLeftEyePosition {
            print("Found left eye at \(face.leftEyePosition)")
        }

        if face.hasRightEyePosition {
            print("Found right eye at \(face.rightEyePosition)")
        }

        if face.hasMouthPosition {
            print("Found mouth at \(face.mouthPosition)")
        }
    }
}