How to convert from YUV to CIImage for iOS

后端 未结 2 1937
小蘑菇
小蘑菇 2020-12-30 17:47

I am trying to convert a YUV image to CIIMage and ultimately UIImage. I am fairly novice at these and trying to figure out an easy way to do it. From what I have learnt, fro

2条回答
  •  长发绾君心
    2020-12-30 18:14

    If you have a video frame object that looks like this:

    int width, 
    int height, 
    unsigned long long time_stamp,
    unsigned char *yData, 
    unsigned char *uData, 
    unsigned char *vData,
    int yStride 
    int uStride 
    int vStride
    

    You can use the following to fill up a pixelBuffer:

    NSDictionary *pixelAttributes = @{(NSString *)kCVPixelBufferIOSurfacePropertiesKey:@{}};
    CVPixelBufferRef pixelBuffer = NULL;
    CVReturn result = CVPixelBufferCreate(kCFAllocatorDefault,
                                            width,
                                            height,
                                            kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,   //  NV12
                                            (__bridge CFDictionaryRef)(pixelAttributes),
                                            &pixelBuffer);
    if (result != kCVReturnSuccess) {
        NSLog(@"Unable to create cvpixelbuffer %d", result);
    }
    CVPixelBufferLockBaseAddress(pixelBuffer, 0);
    unsigned char *yDestPlane = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0);
    for (int i = 0, k = 0; i < height; i ++) {
        for (int j = 0; j < width; j ++) {
            yDestPlane[k++] = yData[j + i * yStride]; 
        }
    }
    unsigned char *uvDestPlane = (unsigned char *)CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 1);
    for (int i = 0, k = 0; i < height / 2; i ++) {
        for (int j = 0; j < width / 2; j ++) {
            uvDestPlane[k++] = uData[j + i * uStride]; 
            uvDestPlane[k++] = vData[j + i * vStride]; 
        }
    }
    

    Now you can convert it to CIImage:

    CIImage *coreImage = [CIImage imageWithCVPixelBuffer:pixelBuffer];
    CIContext *tempContext = [CIContext contextWithOptions:nil];
    CGImageRef coreImageRef = [tempContext createCGImage:coreImage
                                            fromRect:CGRectMake(0, 0, width, height)];
    

    And UIImage if you need that. (image orientation can vary depending on your input)

    UIImage *myUIImage = [[UIImage alloc] initWithCGImage:coreImageRef
                                        scale:1.0
                                        orientation:UIImageOrientationUp];
    

    Don't forget to release the variables:

    CVPixelBufferRelease(pixelBuffer);
    CGImageRelease(coreImageRef);
    

提交回复
热议问题