CIDetector 在处理 CMSampleBuffer 时崩溃

CIDetector crashing while processing CMSampleBuffer

问题: 我正在尝试通过 CIDetector 从 AVCaptureVideoDataOutput 的 CMSampleBuffer 获取面部特征。在执行程序时,10 次中有 9 次程序崩溃,只有一次运行正常。

预期输出: 运行 没有崩溃并在特征检测时打印“Happy”。

代码:

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    
    let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)!
    let opaqueBuffer = Unmanaged<CVImageBuffer>.passUnretained(imageBuffer).toOpaque()
    let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(opaqueBuffer).takeUnretainedValue()
    let sourceImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil)
    let options = [CIDetectorSmile : true as AnyObject, CIDetectorEyeBlink: true as AnyObject, CIDetectorImageOrientation : 6 as AnyObject]
    
    // The detector is nil
    let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: options) 
    let features = detector!.features(in: sourceImage, options: options)

        for feature in features as! [CIFaceFeature] {

            if (feature.hasSmile) {
                printLog(item: "HAPPY")
            }
        }
}

崩溃日志: Unexpectedly found nil while unwrapping an Optional value. detector 为零

希望得到帮助和进一步的指点。

return 是可选的,sampleBuffer 被称为太重了你只能这样做

if let detector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: options) {
    let features = detector.features(in: sourceImage, options: options) 
    for feature in features as! [CIFaceFeature] { 
        if (feature.hasSmile) {
            printLog(item: "HAPPY")
        }
    }
}