我正在使用AVFoundation拍摄视频而我正以kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
格式录制。我想直接从YpCbCr格式的Y平面制作灰度图像。
我尝试通过调用CGContextRef
来创建CGBitmapContextCreate
,但问题是,我不知道要选择哪种色彩空间和像素格式。
- (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.
PS:对不起我的英文。
答案 0 :(得分:2)
如果我没弄错的话,你不应该通过CGContext
。相反,您应该创建一个数据提供者,然后直接创建图像。
代码中的另一个错误是使用kCVPixelFormatType_1Monochrome
常量。它是视频处理(AV库)中使用的常量,而不是Core Graphics(CG库)中使用的常量。只需使用kCGImageAlphaNone
即可。每个像素需要一个单独的组件(灰色)(而不是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);