gpt4 book ai didi

swift - 为什么我不能读取那些 MTLTexture 像素?

转载 作者:行者123 更新时间:2023-12-03 09:23:26 27 4
gpt4 key购买 nike

我正在尝试获取 MTLTexture 的像素这边走:

let pixelCount = compareTexture.width * compareTexture.height

let region = MTLRegionMake2D(0, 0, compareTexture.width, compareTexture.height)

var textureComponentsArray = Array<float4>(repeating: float4(0), count: pixelCount)

textureComponentsArray.withUnsafeMutableBytes {
compareTexture.getBytes($0.baseAddress!, bytesPerRow: (MemoryLayout<float4>.size * compareTexture.width), from: region, mipmapLevel: 0)
}

print(textureComponentsArray.first!)

不幸的是,大多数元素要么是 NaN 要么等于我初始化我的 textureComponentsArray 的值。例如,此代码打印:
float4(nan, nan, nan, nan)

我在 macOS 上,我的 MTLTexture 具有以下属性:
let textureDescriptor = MTLTextureDescriptor()
textureDescriptor.width = imageTexture.width
textureDescriptor.height = imageTexture.height
textureDescriptor.pixelFormat = imageTexture.pixelFormat
textureDescriptor.resourceOptions = .storageModeManaged
textureDescriptor.storageMode = .managed
textureDescriptor.usage = [.renderTarget, .shaderRead, .shaderWrite]

我确实使用托管存储模式,因此数据应该可供 CPU 使用,我不明白为什么它不起作用。

谢谢你。

编辑:
我正在尝试使用:
blitCommandEncoder.synchronize(resource: compareTexture)

我确实等待命令缓冲区完成,但问题仍然存在。

最佳答案

我需要针对 iOS 的这个问题的答案。我要离开我为我的需要编写的扩展程序。

import Metal

extension MTLTexture {
func getPixels<T> (_ region: MTLRegion? = nil, mipmapLevel: Int = 0) -> UnsafeMutablePointer<T> {
let fromRegion = region ?? MTLRegionMake2D(0, 0, self.width, self.height)
let width = fromRegion.size.width
let height = fromRegion.size.height
let bytesPerRow = MemoryLayout<T>.stride * width
let data = UnsafeMutablePointer<T>.allocate(capacity: bytesPerRow * height)

self.getBytes(data, bytesPerRow: bytesPerRow, from: fromRegion, mipmapLevel: mipmapLevel)
return data
}
}
您可以简单地调用该函数。但请记住,您负责释放用于数据对象的内存。
如果像素的格式不同,您也可以读取它们。对于 MTLPixelFormat.rgba32Float我正在检索数据为:
let pixels: UnsafeMutablePointer<Float32> = texture.getPixels()
defer {
pixels.deallocate()
}

let capacity = texture.width * texture.height * MemoryLayout<Float32>.stride

for i in stride(from: 0, to: capacity, by: 4) {
let l = pixels[i + 0]
let a = pixels[i + 1]
let b = pixels[i + 2]
let alpha = pixels[i + 3]
}

关于swift - 为什么我不能读取那些 MTLTexture 像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41577800/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com