问题:我试图通过CIDetector从CMSampleBuffer从AVCaptureVideoDataOutput获取面部特征。在程序执行时,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. The detector is nil
希望得到帮助和更多的指点。
发布于 2021-02-13 16:01:18
返回值是可选的,而且调用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")
}
}
}https://stackoverflow.com/questions/66182937
复制相似问题