swift - 具有 r32Float 像素格式的 MTLTexture 到位图

标签 swift macos metal

我有一个带有 .r32Float 像素格式的 MTLTexture,其值在 0 - 1 范围内。

将该纹理转换为 8 位或 16 位 NSBitmapImageRep 的最佳方法是什么?

最佳答案

大概您希望您的图像处于灰度色彩空间中。这很简单,如果冗长的话,使用 vImage:

let width = texture.width
let height = texture.height
let sourceRowBytes = width * MemoryLayout<Float>.size
let floatValues = UnsafeMutablePointer<Float>.allocate(capacity: width * height)
defer {
    floatValues.deallocate()
}
texture.getBytes(floatValues,
                 bytesPerRow: sourceRowBytes,
                 from: MTLRegionMake2D(0, 0, width, height),
                 mipmapLevel: 0)
var sourceBuffer = vImage_Buffer(data: floatValues,
                                 height: vImagePixelCount(height),
                                 width: vImagePixelCount(width),
                                 rowBytes: sourceRowBytes)
let destRowBytes = width
let byteValues = malloc(width * height)!
var destBuffer = vImage_Buffer(data: byteValues,
                               height: vImagePixelCount(height),
                               width: vImagePixelCount(width),
                               rowBytes: destRowBytes)
vImageConvert_PlanarFtoPlanar8(&sourceBuffer, &destBuffer, 1.0, 0.0, vImage_Flags(kvImageNoFlags))
let bytesPtr = byteValues.assumingMemoryBound(to: UInt8.self)
let provider = CGDataProvider(data: CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
                                                                bytesPtr,
                                                                width * height,
                                                                kCFAllocatorDefault))!
let colorSpace = CGColorSpace(name: CGColorSpace.linearGray)!
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let image = CGImage(width: width,
                    height: height,
                    bitsPerComponent: 8,
                    bitsPerPixel: 8,
                    bytesPerRow: destRowBytes,
                    space: colorSpace,
                    bitmapInfo: bitmapInfo,
                    provider: provider,
                    decode: nil,
                    shouldInterpolate: false,
                    intent: .defaultIntent)!
let imageRep = NSBitmapImageRep(cgImage: image)

关于swift - 具有 r32Float 像素格式的 MTLTexture 到位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51864442/

相关文章:

ios - collectionView 函数 didSelectItemAt indexPath 将数据传递到下一个 View Controller

ios - tableView reloadData cellForRowAtIndexPath 未调用

ios - 在 UILabel 上写入 RTL 字符串

macos - 安装 Apache Spark 后无法从 Mac 上的任何目录运行 pyspark 命令

SwiftUI List() 在 macOS 上不显示 .children

macos - 串行端口挂起

metal - Metal 文本渲染

ios - swift/XCode 6.4 : how to programmatically change the height of cells in table view controller

ios - Metal或OpenGLES中的片段着色器中的共享变量

Swift:将 int 元组转换为包含 float 向量的自定义类型