问题 将UIImage转换为CVPixelBufferRef


我想将UIImage对象转换为CVPixelBufferRef对象,但我绝对不知道。我找不到任何像这样的代码示例代码。

有人可以帮帮我吗? THX提前!

C YA


10452
2017-10-01 11:22


起源

看到 stackoverflow.com/a/44475334/1418457 - onmyway133


答案:


有不同的方法,这些函数转换像素缓冲区 CGImageUImage 是一个包装 CGImage,因此要获得CGImage,您只需要调用该方法 .CGImage
其他方式也创造了一个 CIImage 从缓冲区(已发布)或使用 Accelerate 框架,这可能是最快但也最难的。

- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
{
    NSDictionary *options = @{
                              (NSString*)kCVPixelBufferCGImageCompatibilityKey : @YES,
                              (NSString*)kCVPixelBufferCGBitmapContextCompatibilityKey : @YES,
                              };

    CVPixelBufferRef pxbuffer = NULL;
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, CGImageGetWidth(image),
                        CGImageGetHeight(image), kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef) options,
                        &pxbuffer);
    if (status!=kCVReturnSuccess) {
        NSLog(@"Operation failed");
    }
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);

    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, CGImageGetWidth(image),
                                                 CGImageGetHeight(image), 8, 4*CGImageGetWidth(image), rgbColorSpace,
                                                 kCGImageAlphaNoneSkipFirst);
    NSParameterAssert(context);

    CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
    CGAffineTransform flipVertical = CGAffineTransformMake( 1, 0, 0, -1, 0, CGImageGetHeight(image) );
    CGContextConcatCTM(context, flipVertical);
    CGAffineTransform flipHorizontal = CGAffineTransformMake( -1.0, 0.0, 0.0, 1.0, CGImageGetWidth(image), 0.0 );
    CGContextConcatCTM(context, flipHorizontal);

    CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
                                           CGImageGetHeight(image)), image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);

    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    return pxbuffer;
}

7
2018-01-25 10:53



你为什么要垂直和水平翻转? - Maxi Mus
@MaxiMus因为UIKit和核心grphics有不同的坐标系 developer.apple.com/library/content/documentation/2DDrawing/... - Andrea
y坐标是,但不是x ......? - Maxi Mus


您可以使用Core Image从UIImage创建CVPixelBuffer。

// 1. Create a CIImage with the underlying CGImage encapsulated by the UIImage (referred to as 'image'):

CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];

// 2. Create a CIContext:

Context *ciContext = [CIContext contextWithCGContext:UIGraphicsGetCurrentContext() options:nil];

// 3. Render the CIImage to a CVPixelBuffer (referred to as 'outputBuffer'):

[self.ciContext render:img toCVPixelBuffer:outputBuffer];

AVFoundation提供了读取视频文件(称为资源)的类,以及从处理(或已经读取)资产到像素缓冲区的其他AVFoundation对象的输出。如果这是您唯一关注的问题,您可以在样本照片编辑扩展示例代码中找到您要查找的内容。

如果您的源是从一系列UIImage对象生成的(可能没有源文件,并且您是从用户生成的内容创建新文件),那么上面提供的示例代码就足够了。

注意:它不是最有效的手段,也不是将UIImage转换为CVPixelBuffer的唯一方法;但是,这是最简单的手段。使用Core Graphics将UIImage转换为CVPixelBuffer需要更多代码来设置属性,例如像素缓冲区大小和颜色空间,Core Image会为您处理这些属性。


2
2018-01-25 10:22



我不确定是什么原因造成的。但是CIContext创建会在多线程上下文中导致错误。奇怪的是,这只发生在我快速处理图像时。当我慢慢地这样做时,这似乎不是问题。 - nnrales
我没有问题,但我已经从iOS可用的每个图像处理框架中了解了所有内容。我必须看到你的代码确定它,但这里有一些尝试:创建一个CIContext的单个共享实例,以重用每个图像;并确保您正在创建正确的上下文。他们各自非常不同;而且,虽然编译器可能允许您创建其中任何一个,但并非所有这些都适用于所有情况。文档得到了很好的改进;请咨询更多。 - James Bush


谷歌永远是你的朋友。搜索“CVPixelBufferRef”第一个结果导致 这个片段 从 snipplr

- (CVPixelBufferRef)fastImageFromNSImage:(NSImage *)image{
CVPixelBufferRef buffer = NULL;

// config
size_t width = [image size].width;
size_t height = [image size].height;
size_t bitsPerComponent = 8; // *not* CGImageGetBitsPerComponent(image);
CGColorSpaceRef cs = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGBitmapInfo bi = kCGImageAlphaNoneSkipFirst; // *not* CGImageGetBitmapInfo(image);
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey, [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey, nil];

// create pixel buffer
CVPixelBufferCreate(kCFAllocatorDefault, width, height, k32ARGBPixelFormat, (CFDictionaryRef)d, &buffer);
CVPixelBufferLockBaseAddress(buffer, 0);
void *rasterData = CVPixelBufferGetBaseAddress(buffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(buffer);

// context to draw in, set to pixel buffer's address
CGContextRef ctxt = CGBitmapContextCreate(rasterData, width, height, bitsPerComponent, bytesPerRow, cs, bi);
if(ctxt == NULL){
    NSLog(@"could not create context");
    return NULL;
}

// draw
NSGraphicsContext *nsctxt = [NSGraphicsContext graphicsContextWithGraphicsPort:ctxt flipped:NO];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:nsctxt];
[image compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
[NSGraphicsContext restoreGraphicsState];

CVPixelBufferUnlockBaseAddress(buffer, 0);
CFRelease(ctxt);

return buffer;
}

不过,不知道这是否有效。 (你的里程可能会谨慎:)


1
2017-11-19 16:16



问题是关于转换a UIImage 至 CVPixelBufferRef不是 NSImage - srgtuszy
关于size_t bytesPerRow = CVPixelBufferGetBytesPerRow(缓冲区)的行;这对我来说是个窍门。所有其他代码示例都使用了一个在该设备上发生错误的魔法常量,能够确定真正的值是关键。谢谢。 - Brian Trzupek


CVPixelBufferRef是核心视频用于摄像机输入的内容。

您可以使用CGBitmapContextCreate从图像创建类似的像素位图,然后将图像绘制到位图上下文中。


0
2017-10-01 18:13



我想要做的是使用AV Foundation为电影添加单帧。这将使用AVAssetWriterInputPixelBufferAdaptor类完成。但是这个类需要CVPixelBufferRef对象。那么,如何将UIImage转换为CVPixelBufferRef对象呢? - Nuker


虽然很晚但是对于需要的人。

 // call like this
    CVPixelBufferRef videobuffer = [self pixelBufferFromCGImage:yourImage.CGImage]; 

//转换的方法

-(CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef)image{

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                             [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey, nil];
    CVPixelBufferRef pxbuffer = NULL;
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, videoSize.width, videoSize.height,
                                          kCVPixelFormatType_32ARGB, (__bridge CFDictionaryRef)options, &pxbuffer);
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);

    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    NSParameterAssert(pxdata != NULL);

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, videoSize.width, videoSize.height, 8, 4*videoSize.width, rgbColorSpace, kCGImageAlphaNoneSkipFirst);
    NSParameterAssert(context);
    CGContextConcatCTM(context, CGAffineTransformIdentity);
    CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image);
    CGColorSpaceRelease(rgbColorSpace);
    CGContextRelease(context);
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);

    return pxbuffer;
}

0
2017-12-27 11:41



我试过这个。使用此功能可以裁剪图像帧。所以这里是解决方案CGContextDrawImage(context,CGRectMake(0,0,videoSize.width,videoSize.height),image); - Talha Ahmad Khan