Iphone AVFoundation-从Y平面获取灰度图像(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)

Iphone AVFoundation-从Y平面获取灰度图像(kCVPixelFormatType_420YpCbCr8BiPlanarFullRange),iphone,core-graphics,avfoundation,grayscale,Iphone,Core Graphics,Avfoundation,Grayscale,我正在使用AVFoundation拍摄视频,并以kCVPixelFormatTypeƤYPCBCRC8BIPLANARFULLRANGE格式录制。我想直接从YpCbCr格式的Y平面生成灰度图像 我试图通过调用CGBitmapContextCreate来创建CGContextRef,但问题是,我不知道要选择什么颜色空间和像素格式 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSamp

我正在使用AVFoundation拍摄视频,并以
kCVPixelFormatTypeƤYPCBCRC8BIPLANARFULLRANGE
格式录制。我想直接从YpCbCr格式的Y平面生成灰度图像

我试图通过调用
CGBitmapContextCreate
来创建
CGContextRef
,但问题是,我不知道要选择什么颜色空间和像素格式

- (void)captureOutput:(AVCaptureOutput *)captureOutput 
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer 
       fromConnection:(AVCaptureConnection *)connection 
{       
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); 
    CVPixelBufferLockBaseAddress(imageBuffer,0);        

    /* Get informations about the Y plane */
    uint8_t *YPlaneAddress = CVPixelBufferGetBaseAddressOfPlane(imageBuffer, 0);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRowOfPlane(imageBuffer, 0);
    size_t width = CVPixelBufferGetWidthOfPlane(imageBuffer, 0);
    size_t height = CVPixelBufferGetHeightOfPlane(imageBuffer, 0);

    /* the problematic part of code */
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    CGContextRef newContext = CGBitmapContextCreate(YPlaneAddress,
    width, height, 8, bytesPerRow, colorSpace, kCVPixelFormatType_1Monochrome);

    CGImageRef newImage = CGBitmapContextCreateImage(newContext); 
    UIImage *grayscaleImage = [[UIImage alloc] initWithCGImage:newImage];

    // process the grayscale image ... 
}
当我运行上述代码时,出现以下错误:

<Error>: CGBitmapContextCreateImage: invalid context 0x0
<Error>: CGBitmapContextCreate: unsupported parameter combination: 8 integer bits/component; 16 bits/pixel; 1-component color space; kCGImageAlphaPremultipliedLast; 192 bytes/row.
:CGBitmapContextCreateImage:无效上下文0x0
:CGBitmapContextCreate:不支持的参数组合:8个整数位/组件;16位/像素;单分量颜色空间;KCGIMAGEAlphaPremultipledLast;192字节/行。

PS:对不起我的英语。

如果我没弄错的话,你不应该通过
CGContext
。相反,您应该创建一个数据提供程序,然后直接创建图像

代码中的另一个错误是使用了
kCVPixelFormatType\u 1monocrome
常量。它是视频处理(AV库)中使用的常量,而不是核心图形(CG库)中使用的常量。只需使用
kgimagealphanone
。每个像素需要一个分量(灰色)(而不是RGB的三个分量)是从颜色空间推导出来的

它可能是这样的:

CGDataProviderRef  dataProvider = CGDataProviderCreateWithData(NULL, YPlaneAdress,
      height * bytesPerRow, NULL);
CGImageRef newImage = CGImageCreate(width, height, 8, 8, bytesPerRow,
      colorSpace, kCGImageAlphaNone, dataProvider, NULL, NO, kCGRenderingIntentDefault);
CGDataProviderRelease(dataProvider);

谢谢!这是从相机获取灰度图像的最快方法吗?@user961912:在YpCbCr中访问视频帧应该是最快的,因为它是本机格式(根据WWDC演示)。对于以下步骤,这取决于最终对图像执行的操作。对于一些应用程序(如条形码扫描),您不需要创建CGImage或UIImage。嘿,Codo,谢谢您的回答!我试图实现一点“相同”的效果,不同的是我试图实现灰度效果,在每一帧(实时视频流)上,你有没有可能告诉我正确的方向?你对灰度效果的要求不是很具体。但是一个具有许多有用效果的好库是非常有用的。