簡體   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