【问题标题】:How to convert a MTLTexture to CVpixelBuffer to write into an AVAssetWriter?如何将 MTLTexture 转换为 CVpixelBuffer 以写入 AVAssetWriter?
【发布时间】:2017-12-04 04:32:59
【问题描述】:

我需要在实时视频上应用过滤器,我正在尝试在 Metal 中执行此操作。

但是在将过滤器编码为目标过滤器后,我遇到了将 MTLTexture 转换为 CVPixelBuffer 的问题。参考(https://github.com/oklyc/MetalCameraSample-master-2)

这是我的代码。

if let pixelBuffer = pixelBuffer {
                CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.init(rawValue: 0))             
                let region = MTLRegionMake2D(0, 0, Int(currentDrawable.layer.drawableSize.width), Int(currentDrawable.layer.drawableSize.height))                    
                let bytesPerPixel = 4;
                let bytesPerRow = CGFloat(bytesPerPixel) * currentDrawable.layer.drawableSize.width

                let tempBuffer = CVPixelBufferGetBaseAddress(pixelBuffer)
                destinationTexture.getBytes(tempBuffer!, bytesPerRow: Int(bytesPerRow), from: region1, mipmapLevel: 0)

                let image = self.imageFromCVPixelBuffer(buffer: pixelBuffer)
                CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags.init(rawValue: 0))

            }

方法 imageFromCVPixelBuffer 如下所示。

func imageFromCVPixelBuffer(buffer: CVPixelBuffer) -> UIImage {

    let ciimage = CIImage(cvPixelBuffer: buffer)
    let context = CIContext(options: nil)
    let cgimgage = context.createCGImage(ciimage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer)))

    let uiimage = UIImage(cgImage: cgimgage!)

    return uiimage
}

这是通过金属渲染图像的屏幕截图

这是将 MTLTexture 转换为 CVPixelBuffer 的同一图像的屏幕截图。

需要将 MTLtexture 转换为 CVPixelBuffer 以写入 AVAssetWriter 然后将其保存到库中。

【问题讨论】:

标签: ios swift metal metalkit metal-performance-shaders


【解决方案1】:

不要那样计算bytesPerRow自己。它被传递给 Metal 以让 Metal 知道如何排列行。您希望 Metal 以 CVPixelBuffer 期望的方式排列它们。因此,您应该使用CVPixelBufferGetBytesPerRow() 来确定值。

【讨论】:

  • 我相信 CVPixelBuffer 中的行是 32 像素对齐的。如果您开始假设这些缓冲区在每行末尾不包含任何填充字节,则会导致问题。
  • 等等,但是你在哪里将像素数据从 mtltexture 复制到 cvpixelbuffer?
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 2017-11-11
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2017-10-03
  • 2012-02-04
相关资源
最近更新 更多