繁体   English   中英

将 MTLTexture 转换为 CVPixelBuffer

[英]Converting MTLTexture to CVPixelBuffer

我目前正在使用 Metal 开发实时过滤器。 在定义我的 CIImage 之后,我将图像渲染到 MTLTexture。

下面是我的渲染代码。 context是由 Metal 支持的 CIContext; targetTexture是附加到我的 MTKView 实例的currentDrawable属性的纹理的别名:

context?.render(drawImage, to: targetTexture, commandBuffer: commandBuffer, bounds: targetRect, colorSpace: colorSpace)

它呈现正确,因为我可以看到在金属视图上显示的图像。

问题是在渲染图像(并显示它)之后,我想提取 CVPixelBuffer 并使用类 AVAssetWriter 将其保存到磁盘。

另一种选择是有两个渲染步骤,一个渲染到纹理,另一个渲染到 CVPixelBuffer。 (但不清楚如何创建这样的缓冲区,或者两个渲染步骤对帧率的影响)

任何帮助将不胜感激,谢谢!

您可以尝试像这样从 MTLTexture 复制原始数据:

var outPixelbuffer: CVPixelBuffer?
if let datas = targetTexture.texture.buffer?.contents() {
    CVPixelBufferCreateWithBytes(kCFAllocatorDefault, targetTexture.width, 
    targetTexture.height, kCVPixelFormatType_64RGBAHalf, datas, 
    targetTexture.texture.bufferBytesPerRow, nil, nil, nil, &outPixelbuffer);
}
+ (void)getPixelBufferFromBGRAMTLTexture:(id<MTLTexture>)texture result:(void(^)(CVPixelBufferRef pixelBuffer))block
{

CVPixelBufferRef pxbuffer = NULL;
 NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey,
                          [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey,
                          nil];
 
size_t imageByteCount = texture.width * texture.height * 4;
void *imageBytes = malloc(imageByteCount);
NSUInteger bytesPerRow = texture.width * 4;
MTLRegion region = MTLRegionMake2D(0, 0, texture.width, texture.height);
[texture getBytes:imageBytes bytesPerRow:bytesPerRow fromRegion:region mipmapLevel:0];

CVPixelBufferCreateWithBytes(kCFAllocatorDefault,texture.width,texture.height,kCVPixelFormatType_32BGRA,imageBytes,bytesPerRow,NULL,NULL,(__bridge CFDictionaryRef)options,&pxbuffer);

if (block) {
    block(pxbuffer);
}
CVPixelBufferRelease(pxbuffer);
free(imageBytes);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM