代码之家  ›  专栏  ›  技术社区  ›  Aakash Dave

处理CMSampleBuffer时CIDetector崩溃

  •  0
  • Aakash Dave  · 技术社区  · 4 年前

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

    代码:

    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 是零

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

    1 回复  |  直到 4 年前
        1
  •  0
  •   Shehata Gamal    4 年前

    返回是可选的,并且 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")
            }
        }
    }
    
    推荐文章