AVFoundation - get a grayscale image from the Y plane (kCVPixelFormatType_420YpCbCr8BiPlanarFullRange)

I use AVFoundation to record video, and I record it in format kCVPixelFormatType_420YpCbCr8BiPlanarFullRange. I want to make a grayscale image directly from the Y plane of the YpCbCr format.

I tried to create CGContextRefby calling CGBitmapContextCreate, but the problem is that I don’t know which color space and pixelformat to choose.

- (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 ... 
}

When I run the code above, I got the following errors:

<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: Sorry for my English.

+3
source share
1 answer

If I'm not mistaken, you should not go through CGContext. Instead, you should create a data provider, and then directly an image.

- 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);
+2

All Articles