从 AVCapturePhotoDelegate 方法中检索 CVPixelBuffer

Retrieving CVPixelBuffer from AVCapturePhotoDelegate methods

我想从 didFinishProcessingPhoto 委托方法中获取一个 pixelBuffer,但它是零。

func capturePhoto() {
        let format = [AVVideoCodecKey: AVVideoCodecType.jpeg]
        let settings = AVCapturePhotoSettings(format: format)
        output.capturePhoto(with: settings, delegate: self)
    }

和扩展名:

extension CaptureSessionManager: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        guard let pixelBuffer = photo.pixelBuffer else {
            return
        }

        bufferSubject.onNext(pixelBuffer)
    }
}

在此之前,我显然是在向会话中添加输出。我应该使用与此委托不同的方法吗?

我看了文档后自己弄明白了。

首先确保将 AVCaptureSession.Preset.photo 用作 sessionPresetsession.sessionPreset = .photo.

然后使用 rawPixeFormatType 很重要,因为将其设置为 jpeg 或 hevc 将不会生成 pixelBuffer。可以这样实现:

guard let availableRawFormat = self.output.availableRawPhotoPixelFormatTypes.first else {
            return
        }

let photoSettings = AVCapturePhotoSettings(rawPixelFormatType: availableRawFormat,
                                                   processedFormat: [AVVideoCodecKey : AVVideoCodecType.hevc])

output.capturePhoto(with: photoSettings, delegate: self)

processedFormat:AVCapturePhotoSettings 初始化是可选的。