如何为高分辨率静止图像和低分辨率(视频)预览配置 AVCaptureSession?

How to configure AVCaptureSession for high res still images and low res (video) preview?

我想使用 AVCaptureSession 捕捉高分辨率静止图像。因此 AVCaptureSession 预设设置为 Photo.

目前为止一切正常。在 iPhone 4 上,最终静态图像分辨率最大为 2448x3264 像素,预览(视频)分辨率为 852x640 像素。

现在,由于分析预览帧以检测场景中的对象,我想降低它们的分辨率。如何才能做到这一点? 我尝试将 AVVideoSettings 与较低的 width/height 设置为 AVCaptureVideoDataOutput,但这会导致以下错误消息:

AVCaptureVideoDataOutput setVideoSettings:] - videoSettings dictionary contains one or more unsupported (ignored) keys: (AVVideoHeightKey, AVVideoWidthKey

所以这似乎不是配置 AVCaptureVideoDataOutput / AVCaptureVideoDataOutputSampleBufferDelegate 接收到的预览帧大小的正确方法。您知道如何配置预览帧的分辨率吗?

欢迎任何建议, 谢谢。

如果要手动指定设置,需要在AVCaptureDevice上设置activeFormat。这将隐式地将会话预设设置为 AVCaptureSessionPresetInputPriority.

activeFormat 需要 AVCaptureDeviceFormat but you can only take one from the list of AVCaptureDevice.formats. You'll need to go through the list and find one that fits your needs. Specifically, check that highResolutionStillImageDimensions is high enough for desired still capture and formatDescription (which needs to be inspected with CMFormatDescription* functions, e.g., CMVideoFormatDescriptionGetDimensions) 匹配您所需的预览设置。

要降低 AVCaptureVideoDataOutput 的输出大小,您可以将比特率设置得较低,从而产生较小的样本大小。

AVCaptureVideoDataOutput 的常用键是:

AVVideoAverageBitRateKey
AVVideoProfileLevelKey
AVVideoExpectedSourceFrameRateKey
AVVideoMaxKeyFrameIntervalKey

例如:

private static let videoCompressionOptionsMedium = [AVVideoAverageBitRateKey : 1750000,
                                                    AVVideoProfileLevelKey : AVVideoProfileLevelH264BaselineAutoLevel,
                                                    AVVideoExpectedSourceFrameRateKey : Int(30),
                                                    AVVideoMaxKeyFrameIntervalKey : Int(30)]

仅作记录:我在瞄准相机时最终在预设 Low 中配置了 AVCaptureSession。一旦触发快门,应用程序就会切换到预设 Photo,执行对焦 运行 并拍照。这样一张照片需要 1 到 2.5 秒,虽然不是很好,但至少是一种解决方法。