代码之家  ›  专栏  ›  技术社区  ›  Shreesha Kedlaya

如何将MTLTexture转换为CVpixelBuffer以写入AVAssetWriter?

  •  3
  • Shreesha Kedlaya  · 技术社区  · 7 年前

    但在将过滤器编码为目标过滤器后,我遇到了将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
    }
    

    这是通过metal进行图像渲染的屏幕截图

    enter image description here

    enter image description here

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

    1 回复  |  直到 7 年前
        1
  •  7
  •   Ken Thomases    7 年前

    不计算 bytesPerRow 你自己就是这样。它被传递给Metal,让Metal知道如何排列行。你需要金属来安排它们 CVPixelBuffer 期待他们。因此,您应该使用 CVPixelBufferGetBytesPerRow() 以确定值。