如何从 iPhone 相机创建灰度 CGImage?

Mic*_*ala 5 core-graphics avfoundation ios swift

我想从 iPhone 相机数据创建灰度 CGImage。我正在使用 AVFoundation 并将像素格式类型设置为

kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,我应该能够从 Y 组件创建灰度图像,因此我实现了如下委托方法:

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
        let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)

        CVPixelBufferLockBaseAddress(imageBuffer, 0)
        let yPlanBufferAddress = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0)

        let width = CVPixelBufferGetWidth(imageBuffer)
        let height = CVPixelBufferGetHeight(imageBuffer)        

        let data = NSData(bytes: yPlanBufferAddress, length: width * height)
        let colorSpace = CGColorSpaceCreateDeviceGray()
        let dataProvider = CGDataProviderCreateWithCFData(data)
        let imageRef = CGImageCreate(width, height, 8, 8, width * 8, colorSpace, CGBitmapInfo.ByteOrderDefault, dataProvider, nil, false, kCGRenderingIntentDefault)
        let img = UIImage(CGImage: imageRef)

        CVPixelBufferUnlockBaseAddress(imageBuffer, 0)
        delegate?.cameraController(self, didCreateImage: img)
    }
Run Code Online (Sandbox Code Playgroud)

但我收到了这样的奇怪图像: 在此输入图像描述

有任何想法吗?

Sat*_*ito 3

您必须获取 Y 平面的“bytesPerRow”,并将其提供给 CGImageCreate。

let bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane( w, 0 );

let imageRef = CGImageCreate(
    width
,   height
,   8
,   8
,   bytesPerRow
Run Code Online (Sandbox Code Playgroud)