【发布时间】:2019-07-23 14:21:24
【问题描述】:
我正在尝试使用金属拉普拉斯算子从 rgb CGImage 生成拉普拉斯算子图像。
当前使用的代码:
if let croppedImage = self.cropImage2(image: UIImage(ciImage: image), rect: rect)?.cgImage {
let commandBuffer = self.commandQueue.makeCommandBuffer()!
let laplacian = MPSImageLaplacian(device: self.device)
let textureLoader = MTKTextureLoader(device: self.device)
let options: [MTKTextureLoader.Option : Any]? = nil
let srcTex = try! textureLoader.newTexture(cgImage: croppedImage, options: options)
let desc = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: srcTex.pixelFormat, width: srcTex.width, height: srcTex.height, mipmapped: false)
let lapTex = self.device.makeTexture(descriptor: desc)
laplacian.encode(commandBuffer: commandBuffer, sourceTexture: srcTex, destinationTexture: lapTex!)
let output = CIImage(mtlTexture: lapTex!, options: [:])?.cgImage
print("output: \(output?.width)")
print("")
}
我怀疑问题出在 makeTexture:
let lapTex = self.device.makeTexture(descriptor: desc)
- 虽然 desc 和 srcTex 包含包括宽度和高度在内的有效数据,但调试器中 lapTex 的宽度和高度无效。
看起来顺序或初始化有误,但找不到。
有人知道出了什么问题吗?
谢谢
【问题讨论】:
-
您似乎没有在命令缓冲区上调用
commit(),这意味着内核永远不会执行。此外,为了将生成的图像内容作为CGImage获取,您需要确保首先执行这些命令finish。您可以通过在提交后在命令缓冲区上调用waitUntilCompleted()来做到这一点。请注意,这将是一个阻塞操作,您应该尽可能避免在主线程上执行此操作。 -
谢谢,这在代码中确实缺少,现在在添加它并调用之后:let output = CIImage(mtlTexture: lapTex!, options: [:])?.cgImage, 仍然得到 nil。你知道如何将其转换为有效的 CIImage 吗?